(function() {
    let FileExplorerTool_NewfolderCustom = function(fe) {
        if (!(this instanceof FileExplorerTool_NewfolderCustom))  return new FileExplorerTool_NewfolderCustom(fe);

        let enabled = false;
        let node = fe.AddToolbarButton('fe_fileexplorer_folder_tool_new_folder', fe.Translate('New Folder'));
        let configModalConfirm = {
            title: "Crear directorio",
            content: '' +
                '<form action="" class="formName2">' +
                '<div class="form-group">' +
                '<label>Ingresa Directorio</label>' +
                '<input type="text" id="nombre_carpeta" placeholder="Nombre del directorio" class="name form-control" required>' +
                '</div>' +
                '</form>',
            icon: "glyphicon glyphicon-question-sign",
            columnClass: 'col-md-offset-6 col-md-12',
            containerFluid: true,
            onContentReady: function () {
                // bind to events
                var jc = this;
                this.$content.find('form').on('submit', function (e) {
                    // if the user submits the form by pressing enter in the field.
                    e.preventDefault();
                    jc.$$ok.trigger('click'); // reference the button and click it
                });
            },
            buttons: {
                ok: {
                    text: "Crear",
                    keys: ['enter'],
                    btnClass: 'hovwhite radius15 noborder txtnextwhite pad-top-bot7 pad-lef-rig20 int-nextgreen nextgreen',
                    action: function () {
                        var nombre_carpeta = $('#nombre_carpeta').val();
                        if (!nombre_carpeta) {
                            $.alert({
                                type: 'red',
                                icon: "glyphicon glyphicon-remove-circle",
                                title: "Error",
                                content: 'Ingresa un nombre válido',
                                columnClass: 'medium'
                            });
                            return false;
                        } else {
                            NewFolderHandler(fe, nombre_carpeta);
                        }
                    }
                },
                cancel: {
                    text: "Cancelar",
                    action: function () {}
                }
            }
        };

        // Handle clicks.
        let ClickHandler = function(e) {
            if (enabled) {
                showModalConfirm(configModalConfirm);
            }
        };

        let NewFolderHandler = function (fe, nomDir) {
            let paths = fe.GetCurrentFolder().GetPath();
            let path = "";

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

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

            let xhr = new fe.PrepareXHR({
                url: "/cgi-cpn/prontus_edit_guardar.cgi",
                params: {
                    _prontus_id: $("body").data("prontus-id"),
                    sbm_accion: "CrearDir",
                    _curr_dir: path,
                    nom_new_file: nomDir
                },
                onsuccess: function(e) {
                    let data = JSON.parse(e.target.response);

                    if (data.status == 1) {
                        fe.RefreshFolders(true);
                    } else {
                        showModalAlert({
                            title: "Error al crear directorio",
                            type: "red",
                            msg: data.msg
                        });
                    }
                },
                onerror: function(e) {
                    showModalAlert({
                        title: "Error al crear directorio",
                        type: "red",
                        msg: "Ocurrió un error al tratar de crear el directorio."
                    });
                }
            });

            xhr.Send();
        };

        node.addEventListener('click', ClickHandler);

        let UpdateToolHandler = function(currfolder, attrs) {
            let prevenabled = enabled;

            enabled = true;

            if (prevenabled !== enabled) {
                if (enabled) {
                    node.classList.remove('fe_fileexplorer_disabled');
                } else {
                    node.classList.add('fe_fileexplorer_disabled');
                }

                fe.ToolStateUpdated();
            }
        };

        fe.addEventListener('update_tool', UpdateToolHandler);

        let DestroyToolHandler = function() {
            node.removeEventListener('click', ClickHandler);
        };

        fe.addEventListener('destroy', DestroyToolHandler);
    };

    window.FileExplorer.RegisterTool(1, FileExplorerTool_NewfolderCustom);
})();