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

Ficheform.AddendaInclude.Manager = function (entryKey, addendaName) {
    this.entryKey = entryKey;
    this.addendaName = addendaName;
    this.infoMap = new Map();
    this.orderArray = null;
    this.toolsId = null;
    this.dialogs = new Ficheform.AddendaInclude.Dialogs(this);
};

Ficheform.AddendaInclude.Manager.map = new Map();

Ficheform.AddendaInclude.Manager.prototype.putInfo = function (documentInfo) {
    this.infoMap.set(documentInfo.blockId, documentInfo);
    this.initActionButtons(documentInfo);
    this.initOrderButtons(documentInfo);
    return this;
};

Ficheform.AddendaInclude.Manager.prototype.deleteInfo = function (documentInfo) {
    $$(documentInfo.blockId).remove();
    this.infoMap.delete(documentInfo.blockId);
    return this;
};

Ficheform.AddendaInclude.Manager.prototype.getEntry = function () {
    return Ficheform.entry(this.entryKey);
};

Ficheform.AddendaInclude.Manager.prototype.checkOrder = function (force) {
    if((!force) && (!this.orderArray)) {
        return this;
    }
    this.orderArray = this.getOrderedInfoArray();
    return this;
};

Ficheform.AddendaInclude.Manager.prototype.getOrderedInfoArray = function () {
    var manager = this;
    var array = new Array();
    manager.$documentList().children().each(function (index, element) {
        let documentBlockId =  element.id;
        if (manager.infoMap.has(documentBlockId)) {
            array.push(manager.infoMap.get(documentBlockId));
        }
    });
    return array;
};

Ficheform.AddendaInclude.Manager.prototype.$documentList = function() {
     return $$(this.getEntry(), {ficheformRole: "document-list"});
};

Ficheform.AddendaInclude.Manager.prototype.sort = function (desc) {
    var orderedInfoArray = this.getOrderedInfoArray();
    var length = orderedInfoArray.length;
    if (length < 2) {
        return false;
    }
    var oldBasenameArray = new Array();
    for(let documentInfo of orderedInfoArray) {
        oldBasenameArray.push(documentInfo.basename);
    }
    orderedInfoArray = orderedInfoArray.sort(function (obj1, obj2) {
        let sortValue = _sort(obj1, obj2);
        if (desc) {
            sortValue = -sortValue;
        }
        return sortValue;
    });
    if (!_hasChange()) {
        return false;
    }
    let $current = $$(orderedInfoArray[0].blockId);
    this.$documentList().prepend($current);
    for(let i = 1; i < length; i++) {
        let $next = $$(orderedInfoArray[i].blockId);
        $current.after($next);
        $current = $next;
    }
    this.checkOrder(true);
    return true;
    
    function _sort(obj1, obj2) {
        if (obj1.basename < obj2.basename) {
            return -1;
        }
        if (obj1.basename > obj2.basename) {
            return 1;
        }
        return 0;
    }
    
    function _hasChange() {
        for(let i = 0; i < length; i++) {
            if (oldBasenameArray[i] !== orderedInfoArray[i].basename) {
                return true;
            }
        }
        return false;
    }
};

Ficheform.AddendaInclude.Manager.prototype.removeExisting = function (documentInfo) {
    var $documentDiv = $$(documentInfo.blockId).addClass("ficheform-document-Removed");
    $$($documentDiv, {showState: "active"}).addClass("hidden");
    $$($documentDiv, {showState: "restore"}).removeClass("hidden");
    documentInfo.isRemoved = true;
    return this;
};

Ficheform.AddendaInclude.Manager.prototype.restoreExisting = function (documentInfo) {
    var $documentDiv = $$(documentInfo.blockId).removeClass("ficheform-document-Removed");
    $$($documentDiv, {showState: "active"}).removeClass("hidden");
    $$($documentDiv, {showState: "restore"}).addClass("hidden");
    documentInfo.isRemoved = false;
    return this;
};

Ficheform.AddendaInclude.Manager.prototype.addCreated = function (documentInfo) {
    var manager = this;
    manager.$documentList().append(Bdf.render("ficheform:addenda/block_created", {
        documentBlockId: documentInfo.blockId,
        basename: documentInfo.basename,
        extensionInfoArray: documentInfo.extensionInfoArray,
        noTab: Ficheform.getOption("noTab")
    }));
    manager.putInfo(documentInfo);    
};

Ficheform.AddendaInclude.Manager.prototype.checkHidden = function () {
    var manager = this;
    var toolsId = this.toolsId;
    var length = manager.$documentList().children().length;
    Ficheform.checkEnumerationCell(this.getEntry(), length);
    _checkHidden("sort_asc", (length > 1));
    _checkHidden("sort_desc", (length > 1));
    _checkHidden("nameedit", (length > 0));
    return this;
    
    
    function _checkHidden(suffix, visible) {
        if (visible) {
            $$(toolsId, suffix).removeClass("hidden");
        } else {
            $$(toolsId, suffix).addClass("hidden");
        }
    }
};

Ficheform.AddendaInclude.Manager.prototype.checkChange = function (documentInfo) {
    var $document = $$(documentInfo.blockId);
    var $basename = $$($document, {ficheformRole: "document-basename"}).text(documentInfo.basename);
    if (documentInfo.type !== "created") {
        if (documentInfo.hasNameChange()) {
            $basename.addClass("ficheform-document-NameChanged");
        } else {
            $basename.removeClass("ficheform-document-NameChanged");
        }
    }
    $$($document, {ficheformRole: "document-extensions"}).html(Bdf.render("ficheform:addenda/extensions", {
        extensionInfoArray: documentInfo.extensionInfoArray,
        noTab: Ficheform.getOption("noTab")
    }));
    return this;
};

Ficheform.AddendaInclude.Manager.prototype.update = function () {
    var manager = this;
    manager.checkHidden();
    var entry = this.getEntry();
    _updateOrder();
    _updateChange();
    _updateRemove();
    _updateCreate();
    _updateAdd();
    Ficheform.signalChange();
    
    
    function _updateOrder() {
        if (!manager.orderArray) {
            return;
        }
        let order = "";
        for(let documentInfo of manager.orderArray) {
            switch(documentInfo.type) {
                case "existing":
                    if (!documentInfo.isRemoved) {
                        order += "id=" + documentInfo.subsetItemId + ";";
                    }
                    break;
                case "added":
                    order += "id=" + documentInfo.subsetItemId + ";";
                    break;
                case "created":
                    order += "bn=" + documentInfo.basename + ";";
                    break;
            }
        }
        $$(entry, {ficheformRole: "orderfield"}).val(order);
    }
    
    function _updateRemove() {
        let remove = "";
        for(let documentInfo of manager.infoMap.values()) {
            if ((documentInfo.type === "existing") && (documentInfo.isRemoved)) {
                remove += documentInfo.subsetItemId + ";";
            }
        }
        $$(entry, {ficheformRole: "removefield"}).val(remove);
    }
    
    function _updateChange() {
        let change = "";
        for(let documentInfo of manager.infoMap.values()) {
            if ((documentInfo.type !== "created") && (documentInfo.hasChange()) && (!documentInfo.isRemoved)) {
                change += documentInfo.subsetItemId + ":" + documentInfo.convertChange() + ";";
            }
        }
        $$(entry, {ficheformRole: "changefield"}).val(change);
    }
    
    function _updateCreate() {
        let create = "";
        for(let documentInfo of manager.infoMap.values()) {
            if (documentInfo.type === "created") {
                create += documentInfo.convertChange() + ";";
            }
        }
        $$(entry, {ficheformRole: "createfield"}).val(create);
    }
    
    function _updateAdd() {
        let add = "";
        for(let documentInfo of manager.infoMap.values()) {
            if (documentInfo.type === "added") {
                add += documentInfo.subsetItemId + ";";
            }
        }
        $$(entry, {ficheformRole: "addfield"}).val(add);
    }
};

Ficheform.AddendaInclude.Manager.prototype.initOrderButtons = function (documentInfo) {
    var manager = this;
    var documentBlockId = documentInfo.blockId;
    $$(documentBlockId).prepend(Bdf.render("ficheform:orderbuttons", {
        genId: documentBlockId,
        noTab: Ficheform.getOption("noTab")
    }));
    Ficheform.initOrderButtons(documentBlockId, $$.one(documentBlockId), function () {
        manager.checkOrder(true).update();
    });
    return this;
};

Ficheform.AddendaInclude.Manager.prototype.initActionButtons = function (documentInfo) {
    var manager = this;
    var documentBlockId = documentInfo.blockId;
    var options;
    switch(documentInfo.type) {
        case "existing": {
            options = {
                restore: true,
                change: false
            };
            break;
        }
        case "added": {
            options = {
                restore: false,
                change: false
            };
             break;
        }
        case "created": {
            options = {
                restore: false,
                change: false
            };
            break;
        }
    }
    $$(documentBlockId).append(Bdf.render("ficheform:addenda/documentbuttons", {
        documentBlockId: documentBlockId,
        noTab: Ficheform.getOption("noTab"),
        options: options
    }));
    $$(documentBlockId, "upload").click(function () {
        manager.dialogs.uploadVersions(documentInfo);
    });
    $$(documentBlockId, "nameedit").click(function () {
        manager.dialogs.editDocumentName(documentInfo);
    });
    $$(documentBlockId, "restore").click(function () {
        manager.restoreExisting(documentInfo).update();
    });
    $$(documentBlockId, "change").click(function () {
        switch(documentInfo.type) {
            case "existing":
                manager.dialogs.changeExisting(documentInfo);
                break;
            case "created":
                manager.dialogs.changeCreation(documentInfo);
                break;
        }
    });
    $$(documentBlockId, "remove").click(function () {
        manager.dialogs.removeDocument(documentInfo);
    });
};

Ficheform.AddendaInclude.Manager.init = function (entry) {
    var entryKey = entry.dataset.ficheformKey;
    var addendaName = entry.dataset.subsetName;
    var manager = new Ficheform.AddendaInclude.Manager(entryKey, addendaName);
    $$(entry, {ficheformRole: "document"}).each(function (index2, documentDiv) {
        manager.putInfo(_initDocumentInfo(documentDiv));
    });
    let $addInput = $$(entry, {ficheformRole: "addfield"});
    let addAllowed = ($addInput.length > 0);
    let toolsId = Bdf.generateId();
    manager.toolsId = toolsId;
    $$(entry, {ficheformRole: "document-input"}).append(Bdf.render("ficheform:addenda/tools", {
        toolsId: toolsId,
        addAllowed: addAllowed,
        addendaTitle: Bdf.Loc.get("subset:addenda_" + addendaName),
        noTab: Ficheform.getOption("noTab")
    }));
    $$(toolsId, "upload").click(function () {
        manager.dialogs.uploadNewDocuments(toolsId);
    });
    $$(toolsId, "create").click(function () {
        manager.dialogs.newCreation();
    });
    if (addAllowed) {
        $$(toolsId, "add").click(function () {
            manager.dialogs.pioche($addInput.attr("id"));
        });
    }
    $$(toolsId, "sort_asc").click(function () {
        if (manager.sort(false)) {
            manager.update();
        }
    });
    $$(toolsId, "sort_desc").click(function () {
        if (manager.sort(true)) {
           manager.update();
        }
    });
    $$(toolsId, "nameedit").click(function () {
        manager.dialogs.editAllNames();
    });
    manager.checkHidden();
    Ficheform.AddendaInclude.Manager.map.set(entryKey, manager);
    return manager;
    
    function _initDocumentInfo(documentDiv) {
        let documentBlockId = documentDiv.id;
        let type;
        if ((documentDiv.dataset.ficheformState) && (documentDiv.dataset.ficheformState === "added")) {
            type = "added";
        } else {
            type = "existing";
        }
        let subsetItemId = documentDiv.dataset.subsetItemId;
        let basename = $$(documentDiv, {ficheformRole: "document-basename"}).text();
        let documentInfo = new Ficheform.AddendaInclude.DocumentInfo(addendaName, type, documentBlockId, subsetItemId, basename);
        $$(documentDiv, {ficheformRole: "document-extensions"}).children("a").each(function (index, element) {
            let extension = $(element).text().substring(1);
            documentInfo.initExtensionInfo(extension);
        });
        return documentInfo;
    }
};


