/* global Bdf,$$,Resource,Overlay,Pane */

Resource.Overlay = {};

Resource.Overlay.showCreationForm = function () {
    if (!Bdf.confirmUnload()) {
        return;
    }
    Overlay.start({
        header: Bdf.Loc.escape("_ ADM-11"),
        content: Bdf.render("resource:overlay/creationform", {
            currentPath: _getCurrentPath(),
            commandKey: "ADM-11",
            commandUrl: Bdf.getCommandUrl("ADM-11")
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ submit.resource.resourcecreation'
            }}),
        formAttrs: {
                action: Bdf.URL + "administration",
                method: "POST"
        },
        ajaxForm: {
            dataType: "json",
            success: function (data, textStatus, jqXHR, $form) {
                var done = Bdf.checkError(data);
                if (done) {
                    Overlay.end($form, function () {
                        Bdf.showCommandMessage(data.commandMessage);
                        Resource.List.update();
                    });
                }
            }
        }
    });
    
    
    function _getCurrentPath() {
        let currentState = Pane.State.build();
        if (currentState.withMain()) {
            let idx = currentState.mainContentKey.lastIndexOf('/');
            if (idx > 0) {
                return currentState.mainContentKey.substring(0, idx + 1);
            }
        }
        return "";
    }
    
};

Resource.Overlay.showNewAppForm = function () {
    Overlay.start({
        header: Bdf.Loc.escape("_ ADM-15"),
        content: Bdf.render("resource:overlay/newappform", {
            commandKey: "ADM-15",
            commandUrl: Bdf.getCommandUrl("ADM-15")
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ submit.resource.newapp'
            }}),
        formAttrs: {
                action: Bdf.URL + "administration",
                method: "POST"
        },
        ajaxForm: {
            dataType: "json",
            success: function (data, textStatus, jqXHR, $form) {
                var done = Bdf.checkError(data);
                if (done) {
                    Overlay.end($form, function () {
                        Bdf.showCommandMessage(data.commandMessage);
                        Resource.List.update();
                    });
                }
            }
        }
    });
    
};


Resource.Overlay.showRemoveConfirm = function (path, varOnly) {
    if (!Bdf.confirmUnload()) {
        return;
    }
    var titleKey, confirmKey, submitKey, commandKey;
    if (varOnly) {
        titleKey = "_ ADM-13";
        confirmKey = "_ label.global.confirmationcheck_remove";
        submitKey = "_ submit.resource.resourceremove";
        commandKey = "ADM-13";
    } else {
        titleKey = "_ ADM-14";
        confirmKey = "_ label.global.confirmationcheck_restore";
        submitKey = "_ submit.resource.resourceremove_restore";
        commandKey = "ADM-14";           
    }
    Overlay.start({
        header: Bdf.Loc.escape(titleKey),
        content: Bdf.render("resource:overlay/removeconfirm", {
            path: path,
            confirmKey: confirmKey,
            commandKey: commandKey,
            commandUrl: Bdf.getCommandUrl(commandKey)
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: submitKey
            }}),
        formAttrs: {
                action: Bdf.URL + "administration",
                method: "POST"
        },
        ajaxForm: {
            dataType: "json",
            success: function (data, textStatus, jqXHR, $form) {
                var done = Bdf.checkError(data);
                if (done) {
                    Pane.clearMain();
                    if ((!varOnly) && (Resource.currentPath) && (Resource.currentPath === path)) {
                        Resource.List.update(function () {
                            Bdf.Ajax.loadStreamText(path, function (streamText) {
                                Resource.Form.load(streamText);
                                Overlay.end($form, function () {
                                    Bdf.showCommandMessage(data.commandMessage);
                                });
                            });
                        });
                    } else {
                        Overlay.end($form, function () {
                            Bdf.showCommandMessage(data.commandMessage);
                            Resource.List.update();
                        });
                    }
                }
            }
        }
    });
};

Resource.Overlay.showResourceDisplay = function (type, path, origins) {
    var displayId = Bdf.generateId();
    var firstLoad = true;
    var titleKey, removeLocKey, isImage, disabled, varOnly;
    if (type === "image") {
        titleKey = "_ title.resource.manage_image";
        isImage = true;
    } else {
        titleKey = "_ title.resource.manage_binary";
        isImage = false;
    }
    if (origins === "var") {
        removeLocKey = "_ link.global.delete";
        varOnly = true;
    } else {
        removeLocKey = "_ link.resource.restore";
        varOnly = false;
    }
    if (origins.indexOf("var") === -1) {
         disabled = true;
    } else {
        disabled = false;
    }
    Overlay.start({
        header: Bdf.Loc.escape(titleKey),
        content: Bdf.render("resource:overlay/resourcedisplay", {
            displayId: displayId,
            isImage: isImage,
            path: path,
            removeLocKey: removeLocKey,
            disabled: disabled,
            commandKey: "ADM-12",
            commandUrl: Bdf.getCommandUrl("ADM-12")
        }),
        afterStart: function (overlayId) {
            $$(displayId, "button_remove").click(function () {
                Overlay.end(overlayId, function () {
                    Resource.Overlay.showRemoveConfirm(path, varOnly);
                });
            });
            $$(displayId, "iframe").on("load", function () {
                if (type === "image") {
                    Resource.Overlay.refreshUri(path, function () {
                        $$(displayId, "imagespan").html("<img src='" + path + "' alt='" + path + "'>");
                    });
                }
                if (firstLoad) {
                    firstLoad = false;
                } else {
                    Resource.List.update();
                    $$(displayId, "button_remove").prop("disabled", false);
                }
            });
        }
    });
};

Resource.Overlay.refreshUri = function(uri, callback) {
    var reload = function () {
        // Force a reload of the iframe
        this.contentWindow.location.reload(true);

        // Remove `load` event listener and remove iframe
        this.removeEventListener('load', reload, false);
        this.parentElement.removeChild(this);

        // Run the callback if it is provided
        if (typeof callback === 'function') {
            callback();
        }
    };

    var iframe = document.createElement('iframe');
    iframe.style.display = 'none';

    // Reload iframe once it has loaded
    iframe.addEventListener('load', reload, false);

    // Only call callback if error occured while loading
    iframe.addEventListener('error', callback, false);
    iframe.src = uri;
    document.body.appendChild(iframe);
};

