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

        let enabled = false;
        let node = fe.AddToolbarButton('fe_fileexplorer_folder_tool_delete', fe.Translate('Delete'));

        let DeleteHandler = function (fe) {
            let paths = fe.GetCurrentFolder().GetPath();
            let path = "";
            let entries = fe.GetSelectedFolderEntries();

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

            let theFile = entries[0].name;
            let xhr = new fe.PrepareXHR({
                url: '/cgi-cpn/prontus_s3_delete.cgi',
                params: {
                    _prontus_id: $("body").data("prontus-id"),
                    file: path + theFile
                },
                onsuccess: function(e) {
                    let data = JSON.parse(e.target.response);

                    if (data.status == 1) {
                        // console.log("RefreshFolders");
                        s3_browser.reloadList = 1;
                        fe.RefreshFolders(true);
                    } else {
                        showModalAlert({
                            title: 'Error al eliminar',
                            type: 'red',
                            msg: data.msg
                        });
                    }

                },
                onerror: function(e) {
                    showModalAlert({
                        title: 'Error al eliminar',
                        type: 'red',
                        msg: "Ocurrió un error al tratar de eliminar el archivo."
                    });
                }
            });

            xhr.Send();
        };

        // Handle clicks.
        let ClickHandler = function(e) {
            if (enabled) {
                showModalConfirm({
                    msg: "Se eliminará el archivo del almacenamiento S3 y no se podrá recuperar. ¿Estás seguro?",
                    type: "blue",
                    icon: "glyphicon glyphicon-question-sign",
                    okTitle: "Eliminar archivo",
                    cancelTitle: "Cancelar",
                    btnClassOk: 'hovwhite radius15 noborder txtnextwhite pad-top-bot7 pad-lef-rig20 int-nextred nextred',
                    cbBtnOK: function () {
                        let s3deleteIgnoreSecondAlert = localStorage.getItem("s3deleteIgnoreSecondAlert");
                        let now = Math.round((new Date()).getTime() / 1000);

                        if (!s3deleteIgnoreSecondAlert || (now - s3deleteIgnoreSecondAlert) > 600) {
                            localStorage.setItem("s3deleteIgnoreSecondAlert", "");

                            let checkbox = '<br><div class="checkbox"> \
                            <label class="control-label"><input type="checkbox" id="ignoreSecondAlert"> Ignorar esta alerta por 10 minutos.</label> \
                            </div>';

                            showModalConfirm({
                                msg: "¿Estás seguro de eliminar el archivo de manera permanente?" + checkbox,
                                type: "red",
                                icon: "glyphicon glyphicon-question-sign",
                                okTitle: "Eliminar archivo",
                                cancelTitle: "Cancelar",
                                btnClassOk: 'hovwhite radius15 noborder txtnextwhite pad-top-bot7 pad-lef-rig20 int-nextred nextred',
                                cbBtnOK: function () {
                                    DeleteHandler(fe);

                                    // console.log("ignoreSecondAlert", $("#ignoreSecondAlert").is(":checked"));

                                    if ($("#ignoreSecondAlert").is(":checked")) {
                                        localStorage.setItem("s3deleteIgnoreSecondAlert", Math.round((new Date()).getTime() / 1000));
                                    }
                                },
                                cbBtnCancel: function () {
                                }
                            });
                        } else {
                            DeleteHandler(fe);
                        }
                    },
                    cbBtnCancel: function () {
                    }
                });
            }
        };

        node.addEventListener('click', ClickHandler);

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

            enabled = (!currfolder.waiting && fe.GetNumSelectedItems());

            // Limite de archivos seleccionados a borrar.
            if (fe.GetNumSelectedItems() > 1) enabled = false;

            if (enabled) {
                let selectedFolderEntries = fe.GetSelectedFolderEntries();

                if (selectedFolderEntries[0].type == "folder") enabled = false;
            }

            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_DeleteCustom);
})();
