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

Balayage.Overlay = {};

Balayage.Overlay.showAddBalayageUnit = function (addCallback) {
    var genId = Bdf.generateId();
    var okId = Bdf.generateId();
    var step = 1;
    var unitType = "";
    var xmlWriter = new XmlWriter({prettyXml: true});
    var fields = {};
    Overlay.start({
        header: Bdf.Loc.escape("_ link.exportation.addbalayageunit"),
        content: Bdf.render("balayage:overlay/addbalayageunit_1", {
            genId: genId,
            unitTypeArray: Balayage.UNITTYPE_ARRAY
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                type: "button",
                id: okId,
                locKey: '_ link.global.ok'
            }}),
        afterStart: function (overlayId) {
            $$(okId).click(function () {
                if (step === 1) {
                    unitType = $$(genId, {_name: "unittype", _checked: true}).val();
                    step = 2;
                    $$(genId).html(Bdf.render("balayage:overlay/addbalayageunit_2", _initContext(unitType)));
                } else {
                    _writeXml();
                    Overlay.end(overlayId, function () {
                        addCallback(xmlWriter.xml);
                    });                    
                }
            });
        }
    });
    
    function _initContext(value) {
        let fieldInfo = _getFieldInfo(value);
        fields = {
            attributes: new Array(),
            filter: new Array(),
            output:new Array(),
            all: new Array()
        };
        _initArray("attributes");
        _initArray("filter");
        _initArray("output");
        return {
            genId: genId,
            fields: fields,
            typeTitleKey: _getTypeTitleKey()
        };
        
        function _getTypeTitleKey() {
            for(let unitType of Balayage.UNITTYPE_ARRAY) {
                if (unitType.value === value) {
                    return unitType.labelKey;
                }
            }
        }
        
        function _initArray(propertyName) {
            for(let fieldName of fieldInfo[propertyName]) {
                let field = Object.assign({name: fieldName}, Balayage.FIELD_MAP[fieldName]);
                fields[propertyName].push(field);
                fields.all.push(field);
            }
        }
        
    }
    
    function _getFieldInfo(value) {
        switch(value) {
            case "unique":
                return {
                    attributes: ["extraction"],
                    filter: [],
                    output: ["path", "xslt", "pattern"]
                };
            case "corpus":
            case "fiche":
                return {
                    attributes: ["extraction"],
                    filter: ["corpus"],
                    output: ["path", "xslt", "pattern"]
                };
            case "thesaurus":
            case "motcle":
                return {
                    attributes: ["extraction"],
                    filter: ["thesaurus"],
                    output: ["path", "xslt", "pattern"]
                };
            case "document":
                return {
                    attributes: [],
                    filter: ["corpus", "addenda", "extensions"],
                    output: ["path", "pattern"]
                };
            case "illustration":
                return {
                    attributes: [],
                    filter: ["album", "albumdim"],
                    output: ["path", "pattern"]
                };
            default:
                return {
                    attributes: [],
                    filter: [],
                    output: []
                };
        }
    }
    
    function _writeXml() {
        let tagName = unitType + "-balayage";
        xmlWriter.startOpenTag(tagName);
        for(let field of fields.attributes) {
            _writeAttribute(field);
        }
        xmlWriter.endOpenTag(tagName);
        for(let field of fields.filter) {
            _writeElement(field);
        }
        xmlWriter.startOpenTag("output");
        for(let field of fields.output) {
            _writeAttribute(field);
        }
        xmlWriter.closeEmptyTag();
        xmlWriter.closeTag(tagName);
        
        function _writeAttribute(field) {
            let value = $$(genId, field.name).val();
            if (!value) {
                return;
            }
            xmlWriter.addAttribute(field.attributeName, value);
        }
        
        function _writeElement(field) {
            let value = $$(genId, field.name).val();
            if (!value) {
                return;
            }
            let tokens = value.split(/[;\s]/);
            for(let token of tokens) {
                token = token.trim();
                if (token.length > 0) {
                    xmlWriter.addSimpleElement(field.tagName, token);
                }
            }
        }
    }
    
    
};


Balayage.Overlay.showRun = function (balayageName) {
    var resultDestinationId = Bdf.generateId();
    Overlay.start({
        header: Bdf.Loc.escape("_ title.exportation.balayagerundialog"),
        content: Bdf.render("balayage:overlay/run", {
            name: balayageName,
            title: "",
            resultDestinationId: resultDestinationId
        }),
        isWaiting: true,
        afterStart: function (overlayId, waitingCallback) {
            $.ajax ({
                url: Bdf.URL + "exportation",
                data: {
                    balayage:  balayageName,
                    cmd: "BalayageRun",
                    json: "balayage-log"
                },
                dataType: "json",
                success: function (data, textStatus) {
                    $$(resultDestinationId).html(Bdf.render("balayage:overlay/run_result", data));
                    waitingCallback();
                }
            });
        }
    });
    
};

Balayage.Overlay.showBalayageCreationForm = function () {
    if (!Bdf.confirmUnload()) {
        return;
    }
    Overlay.start({
        header:Bdf.Loc.escape("_ EXP-51"),
        content: Bdf.render("balayage:overlay/balayagecreationform", {
            commandKey: "EXP-51",
            commandUrl: Bdf.getCommandUrl("EXP-51")
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ submit.exportation.balayagecreation'
            }}),
        formAttrs: {
            action: Bdf.URL + "exportation",
            method: "POST"
        },
        ajaxForm: {
            dataType: "json",
            success: function (data, textStatus, jqXHR, $form) {
                let done = Bdf.checkError(data);
                if (done) {
                    Pane.clearMain();
                    Overlay.end($form, function() {
                        Bdf.showCommandMessage(data.commandMessage);
                        Balayage.insertBalayage(data.balayage);
                    });
                }
            }
        }
    });
};

Balayage.Overlay.showBalayageRemoveConfirm = function (balayageName) {
    if (!Bdf.confirmUnload()) {
        return;
    }
    Overlay.start({
        header: Bdf.Loc.escape("_ EXP-52"),
        content: Bdf.render("balayage:overlay/balayageremoveconfirm", {
            balayageName: balayageName,
            title: "",
            commandKey: "EXP-52",
            commandUrl: Bdf.getCommandUrl("EXP-52")
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ submit.balayage.remove'
            }}),
        formAttrs: {
            action: Bdf.URL + "exportation",
            method: "POST"
        },
        ajaxForm: {
            dataType: "json",
            success: function (data, textStatus, jqXHR, $form) {
                let done = Bdf.checkError(data);
                if (done) {
                    Overlay.end($form, function () {
                        Bdf.showCommandMessage(data.commandMessage);
                        Balayage.removeBalayage(balayageName);
                    });
                }
            }
        }
    });
};


Balayage.Overlay.showContentCreationForm = function (balayageName) {
    if (!Bdf.confirmUnload()) {
        return;
    }
    Overlay.start({
        header: Bdf.Loc.escape("_ EXP-54"),
        content: Bdf.render("balayage:overlay/contentcreationform", {
            balayageName: balayageName,
            title: "",
            commandKey: "EXP-54",
            commandUrl: Bdf.getCommandUrl("EXP-54")
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ submit.balayage.contentcreation'
            }}),
        formAttrs: {
                action: Bdf.URL + "exportation",
                method: "POST"
        },
        ajaxForm: {
            dataType: "json",
            success: function (data, textStatus, jqXHR, $form) {
                let done = Bdf.checkError(data);
                if (done) {
                    let valueArray = data.commandMessage.values;
                    let contentPath = valueArray[1];
                    Balayage.updateBalayage(data.balayage);
                    Pane.clearMain();
                    Bdf.Ajax.loadBalayageContent(balayageName, contentPath, function (balayageContent) {
                        Balayage.ContentForm.load(balayageContent, false);
                        Overlay.end($form, function () {
                            Bdf.showCommandMessage(data.commandMessage);
                        });
                    });
                }
            }
        }
    });
};

Balayage.Overlay.showContentRemoveConfirm = function (balayageName, contentPath) {
    Overlay.start({
        header: Bdf.Loc.escape("_ EXP-55"),
        content: Bdf.render("balayage:overlay/contentremoveconfirm", {
            balayageName: balayageName,
            title: "",
            contentPath: contentPath,
            commandKey: "EXP-55",
            commandUrl: Bdf.getCommandUrl("EXP-55")
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ submit.balayage.contentremove'
            }}),
        formAttrs: {
            action: Bdf.URL + "exportation",
            method: "POST"
        },
        ajaxForm: {
            dataType: "json",
            success: function (data, textStatus, jqXHR, $form) {
                let done = Bdf.checkError(data);
                if (done) {
                    Overlay.end($form, function () {
                        Bdf.showCommandMessage(data.commandMessage);
                        Pane.clearMain();
                        Balayage.updateBalayage(data.balayage);
                    });
                }
            }
        }
    });
};

