/* global Bdf,Transformation,CodeMirror,Overlay,$$,Pane */

Transformation.Overlay = {};

/******************************************************************************
* Appel des différents formulaires
******************************************************************************/
Transformation.Overlay.showTemplateCreationForm = function (transformationKey) {
    if (!Bdf.confirmUnload()) {
        return;
    }
    var $transformation = $$({role: "transformation", transformationKey: transformationKey});
    var formId = Bdf.generateId();
    var withPropertiesOdt, tableExportArray;
    _initPropertiesInfo();
    var corpusOptions = null;
    if (transformationKey === "compilation") {
        corpusOptions = Transformation.subsetTrees.toSelectOptions("corpus");
    }
    Overlay.start({
        header: Bdf.Loc.escape("_ EXP-31"),
        content: Bdf.render("transformation:overlay/templatecreationform", {
            transformationKey: transformationKey,
            formId: formId,
            title: $$($transformation, {role: "transformation-title"}).html(),
            corpusOptions: corpusOptions,
            withFragment: Transformation.hasFragmentTemplate(transformationKey),
            withOdt: Transformation.hasOdtTemplate(transformationKey),
            withPropertiesOdt: withPropertiesOdt,
            withExtraction: Transformation.hasExtractionDef(transformationKey),
            tableExportArray: tableExportArray,
            commandKey: "EXP-31",
            commandUrl: Bdf.getCommandUrl("EXP-31")
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: "_ submit.transformation.templatecreation"
            }}),
        afterStart: function () {
            $$(formId, "typeselect").change(function () {
                _typeChange(this);
            });
        },
        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);
                        let newTemplateDescription = Transformation.insertTemplateDescription(data.templateDescription);
                        Transformation.MetadataForm.load(newTemplateDescription.key);
                    });
                 }
            }
        }
    });
    
    function _initPropertiesInfo() {
        let contentPath = transformationKey + ".txt";
        withPropertiesOdt = Transformation.hasPropertiesOdtTemplate(transformationKey);
        tableExportArray = [];
        if (withPropertiesOdt) {
            for(let tableExport of Bdf.Collections.tableExportArray) {
                if (__isHere(tableExport)) {
                    tableExportArray.push(tableExport);
                }
            }
        }
        
        function __isHere(tableExport) {
            for(let content of tableExport.contentArray) {
                if (content.path === contentPath) {
                    return true;
                }
            }
            return false;
        }
    }
    
    
    function _typeChange(typeSelect) {
        let option = typeSelect.options[typeSelect.selectedIndex].value;
        if (option === "odt_properties") {
            $$(formId, "options", "properties").removeClass("hidden");
            $$(formId, "options", "xslt").addClass("hidden");
        } else {
            $$(formId, "options", "properties").addClass("hidden");
            $$(formId, "options", "xslt").removeClass("hidden");
        }
    }
};

Transformation.Overlay.showTemplateRemoveConfirm = function (templateKey) {
    var templateDescription = Transformation.getTemplateDescription(templateKey);
    if (!templateDescription) {
        return;
    }
    Overlay.start({
        header: Bdf.Loc.escape("_ EXP-32"),
        content: Bdf.render("transformation:overlay/templateremoveconfirm", {
            templateKey: templateKey,
            title: templateDescription.title,
            commandKey: "EXP-32",
            commandUrl: Bdf.getCommandUrl("EXP-32")
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ submit.transformation.templateremove'
            }}),
        formAttrs: {
            action: Bdf.URL + "exportation",
            method: "POST"
        },
        ajaxForm: {
            dataType: "json",
            success: function (data, textStatus, jqXHR, $form) {
                var done = Bdf.checkError(data);
                var commandMessage = data.commandMessage;
                if (done) {
                    Overlay.end($form, function () {
                        Bdf.showCommandMessage(commandMessage);
                        Transformation.removeTemplate(templateKey);
                    });
                }
            }
        }
    });
};

Transformation.Overlay.showTemplateContentRemoveConfirm = function (templateKey, path) {
    var templateDescription = Transformation.getTemplateDescription(templateKey);
    if (!templateDescription) {
        return;
    }
    Overlay.start({
        header: Bdf.Loc.escape("_ EXP-34"),
        content: Bdf.render("transformation:overlay/templatecontentremoveconfirm", {
            templateKey: templateKey,
            title: templateDescription.title,
            completeName: Transformation.split(templateKey).templateName,
            path: path,
            commandKey: "EXP-34",
            commandUrl: Bdf.getCommandUrl("EXP-34")
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ submit.transformation.templatecontentremove'
            }}),
        formAttrs: {
            action: Bdf.URL + "exportation",
            method: "POST"
        },
        ajaxForm: {
            dataType: "json",
            success: function (data, textStatus, jqXHR, $form) {
                var done = Bdf.checkError(data);
                if (done) {
                    Pane.clearMain();
                    Overlay.end($form, function() {
                        Bdf.showCommandMessage(data.commandMessage);
                        Transformation.updateTemplateDescription(data.templateDescription);
                    });
                }
            }
        }
    });
};

Transformation.Overlay.showExtractionTest = function (templateKey) {
    var extractionTestPath = Transformation.getTestPath(templateKey) + ".xml";
    if (Transformation.isCompilation(templateKey)) {
        extractionTestPath += "?limit=1";
    }
    var testAreaId = Bdf.generateId();
    Overlay.start({
        header: Bdf.Loc.escape("_ title.transformation.extractiontest"),
        content: Bdf.render("transformation:overlay/extractiontest", {
            testAreaId: testAreaId
        }),
        footer: "",
        afterStart: function () {
            var options = {
                theme: 'bdf',
                lineWrapping: false,
                lineNumbers: true,
                editable: false,
                indentUnit: 4,
                mode: "xml"
            };
            var codeMirror = Bdf.toCodeMirror(testAreaId, options);
            $.ajax({
                url: extractionTestPath,
                dataType: "text",
                success: function (data) {
                    codeMirror.setValue(data);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $$(testAreaId, "error").html(Transformation.Overlay.getErrorText(jqXHR));
                }
            });
        }
    });
};

Transformation.Overlay.showSimpleTemplateTest = function (templateKey) {
    var htmlTestPath = Transformation.getTestPath(templateKey) + ".html";
    if (Transformation.isCompilation(templateKey)) {
        htmlTestPath += "?limit=1";
    }
    var frameId = Bdf.generateId();
    Overlay.start({
        header: Bdf.Loc.escape("_ title.transformation.simpletemplatetest"),
        content: Bdf.render("transformation:overlay/simpletemplatetest", {
            url: htmlTestPath,
            frameId: frameId
        }),
        closeKey: "F1",
        footer: "",
         afterStart: function (overlayId) {
            $$(frameId).on("load", function (event) {
                try {
                    Overlay.addEscapeKeyHandler(this.contentDocument);
                } catch(error) {
                    Bdf.log(error);
                }
            });
        }
    });
};

Transformation.Overlay.showOdFileTest = function (templateKey, file) {
    var odFileTestPath = Transformation.getTestPath(templateKey).replace(".odt", _getExtension());
    if (Transformation.isCompilation(templateKey)) {
        odFileTestPath += "?limit=1";
    }
    var testAreaId = Bdf.generateId();
    Overlay.start({
        header: Bdf.Loc.escape("_ title.transformation.odfiletest", file),
        content: Bdf.render("transformation:overlay/odfiletest", {
            testAreaId: testAreaId
        }),
        closeKey: "F1",
        footer: "",
        afterStart: function () {
            var options = {
                theme: 'bdf',
                lineWrapping: false,
                lineNumbers: true,
                editable: false,
                indentUnit: 4,
                mode: "xml"
            };
            var codeMirror = Bdf.toCodeMirror(testAreaId, options);
            $.ajax({
                url: odFileTestPath,
                dataType: "text",
                success: function (data) {
                    codeMirror.setValue(data);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $$(testAreaId, "error").html(Transformation.Overlay.getErrorText(jqXHR));
                }
            });
        }
    });
    
    function _getExtension() {
        switch(file) {
            case "content.xml":
                return ".odcontent";
            case "styles.xml":
                return ".odstyles";
        }
    }
};

Transformation.Overlay.showBinaryUpdate = function (templateKey, path) {
    Overlay.start({
        header: Bdf.Loc.escape("_ EXP-36"),
        content: Bdf.render("transformation:overlay/binaryupdate", {
            templateKey: templateKey,
            path: path,
            commandKey: "EXP-36",
            commandUrl: Bdf.getCommandUrl("EXP-36")
        }),
        footer: ""
    });
};

Transformation.Overlay.showTemplateDuplicate = function (templateKey, path) {
    var templateDescription = Transformation.getTemplateDescription(templateKey);
    if (!templateDescription) {
        return;
    }
    var split = Transformation.split(templateKey);
    var corpusOptions = null;
    if (split.subsetName) {
        corpusOptions = Transformation.subsetTrees.toSelectOptions("corpus", false, null, split.subsetName);
    }
    Overlay.start({
        header: Bdf.Loc.escape("_ EXP-37"),
        content: Bdf.render("transformation:overlay/templateduplicate", {
            templateKey: templateKey,
            title: templateDescription.title,
            corpusOptions: corpusOptions,
            commandKey: "EXP-37",
            commandUrl: Bdf.getCommandUrl("EXP-37")
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ submit.transformation.templateduplicate'
            }}),
        formAttrs: {
            action: Bdf.URL + "exportation",
            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);
                        Transformation.insertTemplateDescription(data.templateDescription);
                    });
                }
            }
        }
    });
};

Transformation.Overlay.showTemplateConvertToOdt = function (templateKey, path) {
    var templateDescription = Transformation.getTemplateDescription(templateKey);
    if (!templateDescription) {
        return;
    }
    Overlay.start({
        header: Bdf.Loc.escape("_ EXP-38"),
        content: Bdf.render("transformation:overlay/templateconverttoodtconfirm", {
            templateKey: templateKey,
            title: templateDescription.title,
            destinationKey: templateKey + ".odt",
            commandKey: "EXP-38",
            commandUrl: Bdf.getCommandUrl("EXP-38")
        }),
        footer: Bdf.render("bdf:overlay-footer", {
            submit: {
                locKey: '_ submit.transformation.templateconverttoodt'
            }}),
        formAttrs: {
            action: Bdf.URL + "exportation",
            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);
                        let newTemplateDescription = data.templateDescription;
                        if (Transformation.containsTemplateDescription(newTemplateDescription.key)) {
                            Transformation.updateTemplateDescription(newTemplateDescription);
                        } else {
                            Transformation.insertTemplateDescription(newTemplateDescription);
                        }
                    });
                }
            }
        }
    });
};

Transformation.Overlay.getErrorText = function (jqXHR) {
    var responseText = jqXHR.responseText;
    var idx = responseText.indexOf("<body>");
    if (idx > 0)  {
        let text = responseText.substring(idx + 6);
        let idx2 = text.indexOf("</body>");
        text = text.substring(0, idx2);
        return text;
    } else {
        return responseText;
    }
};
