let Editor = {
    idEditor: "ace-editor",
    aceEditor: null,
    fe: null,
    currentEditFile: "",
    currentEntries: [],
    init: function (curr_path) {
        let elem = document.getElementById('filemanager');
        let initpath = [
            [ "", "/", { canmodify: false } ]
        ];

        if (curr_path) {
            let parts = curr_path.split("/");

            parts.forEach(function (item) {
                if (item != "") {
                    initpath.push([item, item]);
                }
            });
        } else {
            let fileEditorCurrentPath = localStorage.getItem("fileEditorCurrentPath");

            if (fileEditorCurrentPath) {
                let parts = fileEditorCurrentPath.split("/");

                parts.forEach(function (item) {
                    if (item != "") {
                        initpath.push([item, item]);
                    }
                });
            } else {
                initpath.push([Admin.prontus_id, Admin.prontus_id]);
            }
        }

        let options = {
            initpath: initpath,
            alwaysfocused: true,
            onfirstrefresh: function (folder) {
                let path = folder.GetPathIDs().join("/");
                // console.log("fileEditorCurrentPath", path);
                localStorage.setItem("fileEditorCurrentPath", path);
                // console.log(folder);
            },
            onrefresh: function(folder, required) {
                let path = folder.GetPathIDs().join("/");
                let $this = this;
                let xhr = new this.PrepareXHR({
                    url: '/cgi-cpn/prontus_list_tree.cgi',
                    params: {
                        _prontus_id: Admin.prontus_id,
                        path: path
                    },
                    onsuccess: function(e) {
                        var data = JSON.parse(e.target.response);

                        if (data.status == 1) {
                            folder.SetEntries(data.data);
                        } else {
                            folder.SetEntries([]);
                            $this.SetNamedStatusBarText('folder', 'No se pudo cargar la carpeta seleccionada.');
                        }

                    },
                    onerror: function(e) {
                    }
                });

                xhr.Send();
            },
            onopenfile: function (folder, entry) {
                $('#file-editor').html('<div class="edit-file-loading"><img src="/prontus/cpan/imag/loader/gears.svg" alt="Cargando..." width="100" class="text-center"></div>');

                let path = folder.GetPathIDs().join("/");

                $("#modal_editar_archivo").modal("show");

                Editor.methods.editFile(entry.path, path)
            },
            langmap: {
                "Download": "Descargar",
                "Delete": "Borrar",
                "Copy": "Copiar",
                "Rename": "Renombrar",
                "New File": "Nuevo archivo",
                "Loading...": "Cargando...",
                "New Folder": "Nueva carpeta",
                "Upload file": "Subir archivo",
                "{0} items": "{0} elemento(s)",
                "{0} items selected {1}": "{0} elementos seleccionados",
                "1 item selected {0}": "1 elemento seleccionado {0}",
                "{0} items selected": "{0} elementos seleccionados",
                "1 item selected": "1 elemento seleccionado",
                "This folder is empty.": "La carpeta está vacía.",
                "Back (Alt + Left Arrow)": "Retroceder",
                "Back to \"{0}\" (Alt + Left Arrow)": 'Retroceder a "{0}"',
                "Forward (Alt + Right Arrow)": "Avanzar",
                "Forward to \"{0}\" (Alt + Right Arrow)": "Avanzar a \"{0}\"",
                "Up (Alt + Up Arrow)": "Arriba",
                "Up to \"{0}\" (Alt + Up Arrow)": "Ir hasta \"{0}\"",
                "1 item": "1 elemento",
                "Recent locations": "Ubicaciones recientes"
            }
        };

        Editor.fe = new window.FileExplorer(elem, options);
        Editor.methods.initUpload();
    },
    methods: {
        editFile: function (file, path) {
            let datos = {
                _prontus_id: Admin.prontus_id,
                _path_file: file,
                _dir: path
            };
            Editor.currentEditFile = file;

            $('#file-editor').load("prontus_edit_file.cgi", datos, function(responseText, textStatus, XMLHttpRequest) {
                if (textStatus == 'success') {
                    if ($('#' + Editor.idEditor).length == 1) {
                        var filename = file.match(/\.\S+/g);
                        filename = filename.toString();
                        filename = filename.replace(/.class/i, "");
                        filename = filename.replace(/\./i, "");
                        Editor.methods.initEditor(filename);

                    } else {
                        Editor.editorLoaded = false;
                    }
                } else {
                    alert("Server error procesando request ajax:\nURL invocada:" +
                        thePath + "\ntextStatus=" +
                        textStatus + "\nresponseText=" +
                        responseText + "\nXMLHttpRequest.status=" +
                        XMLHttpRequest.status + '-' + XMLHttpRequest.statusText +
                        "\nXMLHttpRequest.responseText=" + XMLHttpRequest.responseText +
                        "\nResponseHeaders=" + XMLHttpRequest.getAllResponseHeaders());
                }
            });
        },
        initEditor: function(filetype) {
            var my_highlight;
            switch (filetype) {
                case "html":
                    my_highlight = "ace/mode/php";
                    break;
                case "js":
                    my_highlight = "ace/mode/javascript";
                    break;
                case "php":
                    my_highlight = "ace/mode/php";
                    break;
                case "css":
                    my_highlight = "ace/mode/css";
                    break;
                case "xml":
                    my_highlight = "ace/mode/xml";
                    break;
                case "pm":
                case "pl":
                    my_highlight = "ace/mode/perl";
                    break;
                default:
                    my_highlight = "ace/mode/text";
            }
            // Se inicia el editor
            Editor.aceEditor = ace.edit("ace-editor");
            Editor.aceEditor.setOptions({
                mode: my_highlight,
                theme: 'ace/theme/chrome',
                enableSnippets: true,
                wrapBehavioursEnabled: true,
                hScrollBarAlwaysVisible: true,
                vScrollBarAlwaysVisible: true,
                autoScrollEditorIntoView: true,
                printMarginColumn: 150,
                wrap:true,
                maxLines: 35,
                minLines: 24,
                useWorker: false
            });
            //Se registran los snippets
            ace.config.loadModule('ace/ext/language_tools', function() {
                Editor.snippetManager = ace.require("ace/snippets").snippetManager;

                ace.config.loadModule("ace/snippets/html", function(m) {
                    if (m) {
                        Editor.snippetManager.files.html = m;
                        m.snippets = Editor.snippetManager.parseSnippetFile(m.snippetText);
                        var newSnippets = Editor.methods.getProntusSnippets();
                        newSnippets.forEach(function(s) {
                            m.snippets.push(s);
                        });
                        Editor.snippetManager.register(m.snippets, m.scope);
                    }
                });
            });

            // Editor.methods.initEditorHandler('ace-editor');

            $("#modal_guardar_archivo").off("click").on("click", function () {
                showModalConfirm({
                    title: "Guardar",
                    content: "¿Deseas guardar el archivo?",
                    icon: "glyphicon glyphicon-question-sign",
                    buttons: {
                        ok: {
                            text: "Guardar",
                            btnClass: 'hovwhite radius15 noborder txtnextwhite pad-top-bot7 pad-lef-rig20 int-nextyellow nextyellow',
                            keys: ['enter'],
                            action: function () {
                                Editor.actions.guardar();
                            }
                        },
                        cancel: {
                            text: "Cancelar",
                            action: function () {}
                        }
                    }
                });
            });

            $('#showHelpSnippet').off("click").on("click", function (e) {
                e.preventDefault();

                Editor.actions.showHelp('snippet', Admin.prontus_id);
            });

            $("#sel_marca_usr, #sel_marca_gral, #sel_marca_ctrl").off("change").on("change", function () {
                Editor.actions.insertMarca(this);
            });
        },
        getProntusSnippets: function() {
            return [{
                name: "if",
                content: "%%if($1)%%\n\t$2\n%%/if%%",
                tabTrigger: "if"
            }, {
                name: "nif",
                content: "%%nif($1)%%\n\t$2\n%%/nif%%",
                tabTrigger: "nif"
            }, {
                name: "macro",
                content: "%%macro($1)%%",
                tabTrigger: "macro"
            }, {
                name: "loop",
                content: "%%loop$1($2)%%\n\t$2\n%%/loop%%",
                tabTrigger: "loop"
            }];
        },
        initEditorHandler: function(id_editor) {
            var h = window.innerHeight;

            if (h > 640 && h < 1215) {
                $('#' + Editor.idEditor).css('height', "650px");
            } else if (h < 640) {
                $('#' + Editor.idEditor).css('height', "330px");
            } else if (h >= 1215) {
                $('#' + Editor.idEditor).css('height', "980px");
            }
        },
        initUpload: function () {
            $('#modal_subir_archivo').on('click', "#btn-subir-archivo", function () {
                if (! $('#btn-subir-archivo').hasClass('disabled')) {
                    Editor.methods.accionUpload();
                    $("#modal_subir_archivo").modal('hide');
                }
            });
        },
        accionUploadLayer: function(show) {
            if (show) {
                $('#upload').show('fast');
            } else {
                $('#upload').hide();
            }
        },
        accionUpload: function() {
            if (Editor.loading) {
                return;
            }
            Editor.methods.accionUploadLayer(false);

            if ($('#name_upload').val() == "[nombre sin extensión]") {
                $('#name_upload').val('');
            }

            let paths = Editor.fe.GetCurrentFolder().GetPath();
            let path = "";

            paths.forEach(function (item) {
                path += item[0] + "/";
            });

            path = path.substring(0, path.length - 1);

            $('#subir_archivo [name="_curr_dir"]').val(path);

            var config = {
                formSelector: '#subir_archivo',
                actionURL: "prontus_edit_upload.cgi"
            };
            var opts = {
                complete: function() {
                    $('#name_upload').val("[nombre sin extensión]");
                    $('#file_upload, .upload-content .upload .file').val('');
                },
                success: function(resp) {
                    if (resp.status == 1) {
                        showSuccessAlert(".get_message", resp.msg);
                        Editor.fe.RefreshFolders(true);
                    } else {
                        showWarningAlert(".get_message", resp.msg);

                        $('#msg-global-edit span a').each(function() {
                            $(this).attr('href', '#').attr('class', 'show-extension').css('cursor', 'pointer');
                        });
                    }
                }
            };
            SubmitForm.submitGenericAjax(config, opts);

        },
        validMarcaParam: function(nomMarca, param) {
            var expr = '';

            if (nomMarca == 'if') {
                expr = /^(\w*|\w+ *= *[^=]+)$/;

            } else if (nomMarca == 'nif') {
                expr = /^\w*$/;

                // IFV, IFVC y NIFV
            } else if ((nomMarca.substr(0, 3) == 'ifv') || (nomMarca == 'nifv')) {
                expr = /^([0-9]+,[0-9]+)?$/;

            } else if (nomMarca == 'loop') {
                expr = /^[0-9]+$/;

            } else if (nomMarca == 'macro') {
                expr = /^([^\\\/:\*\?"><\|\s]+)?$/;
            }

            var found = expr.exec(param);
            if (!found) {
                alert('Parámetros no válidos para ' + nomMarca);
                return false;
            }
            return true;
        }
    },
    actions: {
        showHelp: function(nomItem, relPathProntus) {
            let msg;

            if (nomItem == 'snippet') {
                msg = 'Los Snippets son trozos de código útiles personalizables que pueden ser incrustados en cualquier tipo ' +
                    'de archivo a través de este Editor.\n\nLos Snippets disponibles se cargan automáticamente ' +
                    'desde los archivos del directorio ' + relPathProntus + '/plantillas/snippets/';
            }
            showModalAlert({
                title: 'Ayuda',
                type: 'green',
                msg: msg
            });
        },
        guardar: function () {
            let textFile = Editor.aceEditor.getValue();
            let paths = Editor.fe.GetCurrentFolder().GetPath();
            let path = "";

            paths.forEach(function (item) {
                path += item[0] + "/";
            });

            path = path.substring(0, path.length - 1);

            let options = {
                url: "prontus_edit_guardar.cgi",
                method: "POST",
                data: {
                    _prontus_id: Admin.prontus_id,
                    _curr_dir: path,
                    sbm_accion: "Guardar",
                    _path_file: Editor.currentEditFile,
                    text_file: textFile
                },
                success: function (response) {
                    if (response.status == 1) {
                        showModalAlert({
                            title: 'Mensaje del servidor',
                            type: 'green',
                            msg: response.msg
                        });
                    } else {
                        showModalAlert({
                            title: 'Mensaje del servidor',
                            type: 'red',
                            msg: response.msg
                        });
                    }
                },
                error: function () {
                    showModalAlert({
                        title: 'Mensaje del servidor',
                        type: 'red',
                        msg: "Ocurrió un error al tratar de guardar el archivo."
                    });
                }
            };

            $.ajax(options);
        },
        insertMarca: function(selectObject) {
            var args = selectObject.options[selectObject.selectedIndex].value;
            var args_arr = args.split(",");

            var nomMarca = args_arr[0];
            var isTag = args_arr[1];
            var param;

            if (nomMarca === '') {
                selectObject.options[0].selected = true;
                return;
            }

            if (isTag) {
                var marca_open = '';
                var marca_close = '';

                if (nomMarca == 'if') {
                    param = prompt("Ingrese parámetros para el if, opciones:\n- Nombre variable (ej: _txt_bajada) ó Variable=valor (ej: NOMBRE=juanito)", "");
                    if ((param === null) || !Editor.methods.validMarcaParam(nomMarca, param)) {
                        selectObject.options[0].selected = true;
                        return;
                    }
                    marca_open = '\n%%if(' + param + ')%%\n';
                    marca_close = '\n%%/if%%\n';

                } else if (nomMarca == 'nif') {
                    param = prompt("Ingrese nombre de la variable para el nif (ej: _txt_bajada)", "");
                    if ((param === null) || !Editor.methods.validMarcaParam(nomMarca, param)) {
                        selectObject.options[0].selected = true;
                        return;
                    }
                    marca_open = '\n%%nif(' + param + ')%%\n';
                    marca_close = '\n%%/nif%%\n';

                } else if ((nomMarca.substr(0, 3) == 'ifv') || (nomMarca == 'nifv')) { // ifv, ifvc y nifv
                    param = prompt("Ingrese parámetros para " + nomMarca + ": div,res (ej: 2,1)", "");
                    if ((param === null) || !Editor.methods.validMarcaParam(nomMarca, param)) {
                        selectObject.options[0].selected = true;
                        return;
                    }
                    marca_open = '\n%%' + nomMarca + '(' + param + ')%%\n';
                    marca_close = '\n%%/' + nomMarca + '%%\n';

                } else if (nomMarca == 'loop') {
                    param = prompt("Ingrese número del loop (ej: 1)", "");
                    if ((param === null) || !Editor.methods.validMarcaParam(nomMarca, param)) {
                        selectObject.options[0].selected = true;
                        return;
                    }
                    marca_open = '\n%%loop' + param + '%%\n';
                    marca_close = '\n%%/loop%%\n';
                }

                var snippet = marca_open + '\t$2' + marca_close;
                // snippets ACE.
                Editor.snippetManager.insertSnippet(Editor.aceEditor, snippet);
                Editor.aceEditor.focus();
            } else {
                var marca = '';

                if (nomMarca == 'macro') {
                    param = prompt("Ingrese nombre de archivo de macro (ej: mimacro.html)", "");
                    if ((param === null) || !Editor.methods.validMarcaParam(nomMarca, param)) {
                        selectObject.options[0].selected = true;
                        return;
                    }
                    marca = '\n%%macro(' + param + ')%%\n';
                } else {
                    marca = '%%' + nomMarca + '%%';
                }

                Editor.snippetManager.insertSnippet(Editor.aceEditor, marca);
                Editor.aceEditor.focus();
            }

            selectObject.options[0].selected = true;
        }
    }
};
