/* global Bdf,Overlay,Ficheform,$$ */

Ficheform.AddendaInclude.Dialogs = function (manager) {
    this.manager = manager;
};

Ficheform.AddendaInclude.Dialogs.prototype.uploadVersions = function (documentInfo) {
    var manager = this.manager;
    var documentBlockId = documentInfo.blockId;
    var callKey = documentBlockId;
    var $currentArea = $$(documentBlockId, "uploadarea");
    if ($currentArea.length > 0) {
        $currentArea.remove();
    } else {
        Bdf.registerFunction("resize/" + callKey, function (height) {
            $$(documentBlockId, "uploadiframe").height(height);
        });
        Bdf.registerCallback(callKey, function (result) {
            for(let tmpFile of result.tmpFileArray) {
                documentInfo.checkTmpFile(tmpFile);
            }
            manager.checkChange(documentInfo).update();
            $$(documentBlockId, "uploadarea").remove();
        });
        $$(documentBlockId).append(Bdf.render("ficheform:addenda/uploadarea", {
            refId: documentInfo.blockId,
            addenda: manager.addendaName,
            callKey: callKey,
            mode: "unique"
        }));
    }    
};

Ficheform.AddendaInclude.Dialogs.prototype.uploadNewDocuments = function (toolsId) {
    var manager = this.manager;
    var callKey = toolsId;
    var $currentArea = $$(toolsId, "uploadarea");
    if ($currentArea.length > 0) {
        $currentArea.remove();
    } else {
        Bdf.registerFunction("resize/" + callKey, function (height) {
            $$(toolsId, "uploadiframe").height(height);
        });
        Bdf.registerObject("options/" + callKey, {
            namingInstruction: Ficheform.AddendaInclude.getNamingInstructionLoc(manager.addendaName)
        });
        Bdf.registerCallback(callKey, function (result) {
            for(let group of result.groupArray) {
                let documentInfo = Ficheform.AddendaInclude.DocumentInfo.newCreated(manager.addendaName, group.normalizedBasename);
                documentInfo.originalName = group.originalBasename;
                for(let tmpFile of group.tmpFileArray) {
                    documentInfo.checkTmpFile(tmpFile);
                }
                manager.addCreated(documentInfo);
            }
            manager.checkOrder(false).update();
            $$(toolsId, "uploadarea").remove();
        });
        $$(toolsId).append(Bdf.render("ficheform:addenda/uploadarea", {
            refId: toolsId,
            addenda: manager.addendaName,
            callKey: callKey,
            mode: "multi"
        }));
    }
};

Ficheform.AddendaInclude.Dialogs.prototype.pioche = function (inputId) {
    var manager = this.manager;
    var limit = manager.getEntry().dataset.ficheformLimit;
    if (!limit) {
        limit = -1;
    }
    var subsets = manager.addendaName;
    var url = "pioche?page=document&subsets=" + subsets + "&callkey=" + inputId + "&limit=" + limit;
    Bdf.registerCallback(inputId, _callback);
    Ficheform.openDialog(url,"pioche_" + manager.entryKey, 430, 510);
    
    
    function _callback(selectionArray) {
        var $documentList = manager.$documentList();
        for(let jsonItem of selectionArray) {
            let code = jsonItem.code;
            let existing = $$($documentList, {addCode: code});
            if (existing.length === 0) {
                let documentBlockId = Bdf.generateId();
                let documentInfo = new Ficheform.AddendaInclude.DocumentInfo(manager.addendaName, "added", documentBlockId, jsonItem.id, jsonItem.basename);
                for(let extension of jsonItem.extensions) {
                    documentInfo.initExtensionInfo(extension);
                }
                $documentList.append(Bdf.render("ficheform:addenda/block_added", {
                    documentBlockId: documentBlockId,
                    id: documentInfo.subsetItemId,
                    code: code,
                    basename: documentInfo.basename,
                    extensionInfoArray: documentInfo.extensionInfoArray,
                    noTab: Ficheform.getOption("noTab")
                }));
                
                manager.putInfo(documentInfo);
            } 
        }
        manager.update();
    }
};

Ficheform.AddendaInclude.Dialogs.prototype.changeExisting = function (documentInfo) {
    var manager = this.manager;
    var entryKey = manager.entryKey;
    var addendaName = manager.addendaName;
    var callKey = entryKey + "/" + documentInfo.blockId;
    Bdf.registerCallback(callKey, _callbackChange);
    var url = "addenda?page=document-change&addenda=" + addendaName + "&changetype=" + Ficheform.AddendaInclude.DOCUMENT_CHANGETYPE + "&callkey=" + callKey;
    url = documentInfo.completeUrl(url);
    Ficheform.openDialog(url,"pioche_"+ entryKey, 620, 580);
    
    
    function _callbackChange(callResponse) {
        documentInfo.checkChangeCall(callResponse);
        manager.checkChange(documentInfo).update();
    }
};

Ficheform.AddendaInclude.Dialogs.prototype.editAllNames = function () {
    var manager = this.manager;
    var orderedInfoArray = manager.getOrderedInfoArray();
    var genId = Bdf.generateId();
    Overlay.start({
        header: Bdf.Loc.escape("_ title.edition.nameedit_all"),
        content: Bdf.render("ficheform:addenda/overlay/nameedit_all", {
            genId: genId,
            documentInfoArray: orderedInfoArray,
            namingInstruction: Ficheform.AddendaInclude.getNamingInstructionLoc(manager.addendaName)
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ link.global.ok'
            }}),
        formAttrs: {
            action: "#"
        },
        formSubmit: function (overlayId, formElement) {
            let array = new Array();
            $$(formElement, {_element: "input"}).each(function (index, element) {
                let documentBlockId = element.name;
                let documentInfo = manager.infoMap.get(documentBlockId);
                if (documentInfo) {
                    documentInfo.basename = element.value;
                    array.push(documentInfo);
                }
            });
            Overlay.end(overlayId, function() {
                for(let documentInfo of array) {
                    manager.checkChange(documentInfo);
                }
                manager.update();
            });
            return false;
        }
    });
};

Ficheform.AddendaInclude.Dialogs.prototype.editDocumentName = function (documentInfo) {
    var manager = this.manager;
    var genId = Bdf.generateId();
    Overlay.start({
        header: Bdf.Loc.escape("_ title.edition.nameedit_document"),
        content: Bdf.render("ficheform:addenda/overlay/nameedit_document", {
            genId: genId,
            basename: documentInfo.basename,
            namingInstruction: Ficheform.AddendaInclude.getNamingInstructionLoc(manager.addendaName)
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ link.global.ok'
            }}),
        formAttrs: {
            action: "#"
        },
        formSubmit: function (overlayId) {
            documentInfo.basename = ID(genId, "input").value;
            Overlay.end(overlayId, function() {
                manager.checkChange(documentInfo).update();
            });
            return false;
        }
    });
    
};

Ficheform.AddendaInclude.Dialogs.prototype.newCreation = function () {
    var manager = this.manager;
    var callKey = manager.entryKey;
    Bdf.registerCallback(callKey, _callback);
    var url = "addenda?page=document-upload-new&addenda=" + manager.addendaName  + "&callkey=" + callKey;
    Ficheform.openDialog(url, "uploadnew_" + callKey, 620, 580);
    
    
    function _callback(callResponse) {
        let documentInfo = Ficheform.AddendaInclude.DocumentInfo.newCreated(manager.addendaName, callResponse.basename);
        documentInfo.checkChangeCall(callResponse);
        manager.addCreated(documentInfo);
        manager.checkOrder(false).update();
    }
};

Ficheform.AddendaInclude.Dialogs.prototype.changeCreation = function (documentInfo) {
    var manager = this.manager;
    var entryKey = manager.entryKey;
    var addendaName = manager.addendaName;
    var callKey = entryKey + "/" + documentInfo.blockId;
    Bdf.registerCallback(callKey, _callback);
    var url = "addenda?page=document-change&addenda=" + addendaName + "&changetype=" + Ficheform.AddendaInclude.CREATION_CHANGETYPE + "&callkey=" + callKey
        + "&originalname=" + encodeURIComponent(documentInfo.originalName)
        + "&change=" + encodeURIComponent(documentInfo.convertChange());
    Ficheform.openDialog(url,"pioche_"+ entryKey, 620, 580);

    
    function _callback(callResponse) {
        documentInfo.checkChangeCall(callResponse);
        manager.checkChange(documentInfo).checkOrder(false).update();
    }
};

Ficheform.AddendaInclude.Dialogs.prototype.removeDocument = function (documentInfo) {
    var manager = this.manager;
    var genId = Bdf.generateId();
    var warningLocKey;
    var allLabelLocKey;
    var extensionInfoArray = documentInfo.extensionInfoArray;
    switch(documentInfo.type) {
        case "existing":
            allLabelLocKey = "_ label.edition.documentremove_existing";
            warningLocKey = "_ warning.edition.documentremove_existing";
             break;
        case "created":
            allLabelLocKey = "_ label.edition.documentremove_created";
            warningLocKey = "";
            break;
        case "added":
            allLabelLocKey = "_ label.edition.documentremove_added";
            warningLocKey = "";
            break;
    }
    
    Overlay.start({
        header: Bdf.Loc.escape("_ title.edition.documentremove"),
        content: Bdf.render("ficheform:addenda/overlay/documentremove", {
            genId: genId,
            warningLocKey: warningLocKey,
            allLabelLocKey: allLabelLocKey,
            selectionDisabled: (extensionInfoArray.length < 2),
            extensionInfoArray: extensionInfoArray
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ link.global.ok'
            }}),
        formAttrs: {
            action: "#"
        },
        afterStart: function (overlayId) {
            Bdf.Deploy.initOverlay(overlayId);
            _checkExtensions();
            $$(genId, {_name:"version"}).on("click", function () {
               _checkExtensions();
            });
        },
        formSubmit: function (overlayId, formElement) {
            let type = $$(formElement, {_name:"type", _checked: true}).val();
            switch(type) {
                case "all": {
                    switch(documentInfo.type) {
                        case "existing":
                            manager.removeExisting(documentInfo);
                            break;
                        default:
                            manager.deleteInfo(documentInfo);
                    }
                    break;
                }
                case "selection": {
                    $$(formElement, {_name:"version"}).each(function (index, element) {
                        documentInfo.setRemoved(element.value, element.checked);
                        manager.checkChange(documentInfo);
                    });
                    break;
                }
            }
            Overlay.end(overlayId, function() {
                manager.update();
            });
            return false;
        }
    });
    
    function _checkExtensions() {
        let $unckeched =  $$(genId, {_name: "version", _checked: false});
        let disabled = ($unckeched.length === 1);
        $unckeched.each(function (index, element) {
            $(element).prop("disabled", disabled);
            if (disabled) {
                $$({_element: "label", _for: element.id}).addClass("ficheform-document-Disabled");
            } else {
                $$({_element: "label", _for: element.id}).removeClass("ficheform-document-Disabled");
            }
        });
    }
    
};
