/* global Bdf,AddendaDoc,$$,Overlay */

AddendaDoc.Change = {};

AddendaDoc.ARGS = {
    clientId: "",
    changeType: "",
    callKey: "",
    addenda: "",
    newName: "",
    originalName: null,
    documentId: null,
    documentName: null,
    extensionArray: [
        {
            extension: "",
            state: "",
            tmpFileName: null,
            tmpUrl: null,
            currentFileName: null
        }
    ]
};

AddendaDoc.Change.init = function (args) {
    var genId = Bdf.generateId();
    $$(args.clientId).html(Bdf.render("document:client-change", {
        args: args,
        genId: genId,
        titleKey: (args.changeType === "document")?"_ title.addenda.documentchange":"_ title.addenda.documentcreate"
    }));
    $$(genId, "cancel").click(function () {
        window.close();
    });
    $$(genId, "confirm").click(_updateCaller).focus();
    $$(genId, "versionupdate").click(_versionUpdate);
    var $list = $$(genId, "list");
   _onClick("remove", function () {
         _versionRemove(this.dataset.extension);
    });
    _onClick("restore", function () {
        _versionRestore(this.dataset.extension);
    });
    if (args.changeType === "document") {
        $$(genId, "versionupdate").focus();
    } else {
        $$(genId, "confirm").focus();
    }
    
    function _onClick(actionName, clickFunction) {
        $list.on("click", $$.toCssSelector({action: actionName}), clickFunction);
    }
    
    function _updateCaller() {
        let newName = $$(genId, "newname").val();
        newName = newName.trim();
        if (newName.length === 0) {
            alert(Bdf.Loc.get("_ error.empty.documentname"));
            return;
        }
        if (!AddendaDoc.testBasename(newName)) {
            alert(Bdf.Loc.get("_ error.wrong.documentname"));
            return;
        }
        if ((args.changeType === AddendaDoc.DOCUMENT_CHANGETYPE) && (args.newName) && (args.newName === newName)) {
            newName = false;
        }
        let callback = window.opener.Bdf.getCallback(args.callKey);
        if (callback) {
            callback({
                changeType: args.changeType,
                callKey: args.callKey,
                extensions: args.extensionArray,
                basename: newName,
                originalName: args.originalName
            });
        }
        window.close();
    }
    
    function _versionRemove(extension) {
        let $extensionItem = $$({itemName: extension});
        if ($extensionItem.length === 0) {
            return;
        }
        if (AddendaDoc.isLastVersion(args.extensionArray, extension)) {
            alert(Bdf.Loc.get("_ error.notremoveable.version"));
            return;
        }
        let extensionObj = _getExtensionObject(extension);
        if (extensionObj.state !== AddendaDoc.REMOVE_STATE) {
            extensionObj.previousState = extensionObj.state;
        }
        extensionObj.state = AddendaDoc.REMOVE_STATE;
        $extensionItem.removeClass("document-extension-Added").removeClass("document-extension-Changed").addClass("document-extension-Removed");
        _displayButton($extensionItem, false);
    }
    
    function _versionRestore(extension) {
        let $extensionItem = $$({itemName: extension});
        if ($extensionItem.length === 0) {
            return;
        }
        $extensionItem.removeClass("document-extension-Removed");
        let extensionObj = _getExtensionObject(extension);
        let newState;
        if (extensionObj.previousState) {
            newState = extensionObj.previousState;
        } else if (extensionObj.tmpFileName) {
            newState = AddendaDoc.UPDATE_STATE;
        } else {
            newState = AddendaDoc.NOCHANGE_STATE;
        }
        if (newState === AddendaDoc.UPDATE_STATE) {
            $extensionItem.addClass("document-extension-Changed");
        } else if (newState === AddendaDoc.CREATE_STATE) {
            $extensionItem.addClass("document-extension-Added");
        }
        extensionObj.previousState = extensionObj.state;
        extensionObj.state = newState;
        _displayButton($extensionItem, true);
    }
    
    function _versionUpdate() {
        let callKey = Bdf.generateId();
        let overlayId = AddendaDoc.Change.showVersionUpdate(args.addenda, callKey);
        Bdf.registerCallback(callKey, function (callResponse) {
            Overlay.end(overlayId, function () {
                if (callResponse) {
                    _versionUpdated(callResponse);
                }
            });
        });
    }
    
    function _versionUpdated(callResponse) {
        let extension = callResponse.extension;
        let tmpFileName = callResponse.tmpFileName;
        let extensionObj = _getExtensionObject(extension);
        if (extensionObj) {
            let currentState = extensionObj.state;
            let newState;
            if (currentState === AddendaDoc.REMOVE_STATE) {
                if (extensionObj.previousState === AddendaDoc.CREATE_STATE) {
                    newState = AddendaDoc.CREATE_STATE;
                } else {
                    newState = AddendaDoc.UPDATE_STATE;
                }
            } else if ((currentState === AddendaDoc.NOCHANGE_STATE) || (currentState === AddendaDoc.UPDATE_STATE))  {
                newState = AddendaDoc.UPDATE_STATE;
            } else {
                newState = AddendaDoc.CREATE_STATE;
            }
            extensionObj.state = newState;
            extensionObj.tmpFileName = tmpFileName;
            let $extensionItem = $$({itemName: extension});
            $extensionItem.removeClass("document-extension-Removed").addClass("document-extension-Changed");
            $extensionItem.find("a").attr("href", Bdf.toTmpPath(callResponse.tmpFileName));
            _displayButton($extensionItem, true);
        } else {
            extensionObj = {
                extension: extension,
                state: AddendaDoc.CREATE_STATE,
                tmpFileName: tmpFileName,
                tmpUrl: Bdf.toTmpPath(tmpFileName)
            };
            $$(genId, "list").append(Bdf.render("document:extension", Object.assign({args: args}, extensionObj)));
            args.extensionArray.push(extensionObj);
        }
    }
    
    function _displayButton($extensionItem, active) {
        if (active) {
            $$($extensionItem, {showState: "restore"}).addClass("hidden");
            $$($extensionItem, {showState: "active"}).removeClass("hidden");
        } else {
            $$($extensionItem, {showState: "restore"}).removeClass("hidden");
            $$($extensionItem, {showState: "active"}).addClass("hidden");
        }
    }
    
    function _getExtensionObject(extension) {
        for(let obj of args.extensionArray) {
            if (obj.extension === extension) {
                return obj;
            }
        }
        return null;
    }
};

AddendaDoc.Change.showVersionUpdate = function (addenda, callKey) {
    var overlayId = Overlay.start({
        header: Bdf.Loc.escape("_ label.addenda.versionupdate"),
        content: Bdf.render("document:overlay/versionupdate", {
            addenda: addenda,
            callKey: callKey
        }),
        footer: "",
        supplementaryClasses: {
            dialog: "addenda-Overlay"
        }
    });
    return overlayId;
};

$(function () {
    Bdf.initTemplates();
    AddendaDoc.Change.init(AddendaDoc.Change.ARGS);
});
