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

        let enabled = false;
        let node = fe.AddToolbarButton('fe_fileexplorer_folder_tool_download', fe.Translate('Download'));

        // Handle clicks.
        let ClickHandler = function(e) {
            if (enabled) {
                let selectedFolderEntries = fe.GetSelectedFolderEntries();
                let downloadFileAnchor = document.getElementById("downloadFile");

                let clickEvent = document.createEvent("MouseEvent");
                clickEvent.initEvent("click", true, true);

                downloadFileAnchor.href = selectedFolderEntries[0].path;
                downloadFileAnchor.download = selectedFolderEntries[0].name;
                downloadFileAnchor.dispatchEvent(clickEvent);

            }
        };

        node.addEventListener('click', ClickHandler);

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

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

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