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

Transformation.List = {};

Transformation.List.SPECIAL_ARRAY = [
    {
        transformationKey: "compilation",
        titleLocKey: "_ label.transformation.templates_compilation"
    },
    {
        transformationKey: "format",
        titleLocKey: "_ label.transformation.templates_format"
    },
    {
        transformationKey: "section",
        titleLocKey: "_ label.transformation.templates_section"
    },
    {
        transformationKey: "statthesaurus",
        titleLocKey: "_ label.transformation.templates_statthesaurus"
    },
    {
        transformationKey: "inversethesaurus",
        titleLocKey: "_ label.transformation.templates_inversethesaurus"
    },
    {
        transformationKey: "memento",
        titleLocKey: "_ label.transformation.templates_memento"
    }
];

Transformation.List.init = function (callback) {
    var corpusTree = Transformation.subsetTrees.getTree("corpus");
    Bdf.Ajax.loadTransformationDescriptions(_toKeys(), function (transformationDescriptions) {
        Transformation.initTemplateDescriptionMap(transformationDescriptions);
        _appendSpecialTransformations(transformationDescriptions);
        _appendCorpusTransformations(transformationDescriptions);
        _checkState();
        Transformation.List.initActions();
        Bdf.Deploy.init($$("layout_list"));
        if (callback) {
            callback();
        }
    });
    
    
    function _appendSpecialTransformations(transformationDescriptionMap) {
        let $specialKeys = $$("listpane_body_specialkeys");
        $specialKeys.empty();
        for(let special of Transformation.List.SPECIAL_ARRAY) {
            $specialKeys.append(Bdf.render("transformation:list/transformation", {
                transformationKey: special.transformationKey,
                specialLocKey: special.titleLocKey,
                transformationDescription: transformationDescriptionMap[special.transformationKey]
            }));
        }
    }
    
    function _appendCorpusTransformations(transformationDescriptionMap) {
        __complete(corpusTree);
        $$("listpane_body_corpuskeys").html(Bdf.render("transformation:list/node", corpusTree));
        
        function __complete(nodeArray) {
            for (let nodeObject of nodeArray) {
                if (nodeObject.node === "subset") {
                    let idx = nodeObject.key.indexOf("_");
                    nodeObject.transformationKey = nodeObject.key;
                    nodeObject.subsetCategory = nodeObject.key.substring(0, idx);
                    nodeObject.subsetName = nodeObject.key.substring(idx +1);
                    nodeObject.transformationDescription = transformationDescriptionMap[nodeObject.key];
                } else if (nodeObject.node === "group") {
                    __complete(nodeObject.array);
                }
            }
        }
    }
    
    function _toKeys() {
        let keyArray = new Array();
        for(let special of Transformation.List.SPECIAL_ARRAY) {
            keyArray.push(special.transformationKey);
        }
        __addKey(corpusTree);
        return keyArray.join(",");
        
        function __addKey(corpusArray) {
            for(let nodeObject of corpusArray) {
                if (nodeObject.node === "subset") {
                    keyArray.push(nodeObject.key);
                } else if (nodeObject.node === "group") {
                    __addKey(nodeObject.array);
                }
            }
        }
    }
    
    function _checkState() {
        $$({role: "transformation"}).each(function (index, element) {
            Transformation.List.checkTransformationState($(element));
        });
    }
};

Transformation.List.initActions = function () {
    $$({action: "newtemplate"}).click(function () {
        Transformation.Overlay.showTemplateCreationForm(_getTransformationKey(this));
        return false;
    });
    var $list = $$("layout_list");
    _onClick("metadata", function () {
        if (!Bdf.confirmUnload()) {
            return false;
        }
        let templateKey = _getTemplateKey(this);
        Pane.loadOrDestock(templateKey, function () {
            Transformation.MetadataForm.load(templateKey);
        });
    });
    _onClick("templateremove", function () {
        Transformation.Overlay.showTemplateRemoveConfirm(_getTemplateKey(this));
    });
    _onClick("extractionreinit", function () {
        Transformation.extractionReinit(_getTemplateKey(this));
    });
    _onClick("templateduplicate", function () {
        Transformation.Overlay.showTemplateDuplicate(_getTemplateKey(this));
    });
    _onClick("templateconverttoodt", function () {
        Transformation.Overlay.showTemplateConvertToOdt(_getTemplateKey(this));
    });
    _onClick("load-main", function () {
        if (!Bdf.confirmUnload()) {
            return false;
        }
        let reference = _getReferenceAncestor(this);
        Pane.loadOrDestock(reference.dataset.contentKey, function () {
            _loadContent(reference, false);
        });
        return false;
    });
    _onClick("load-stock", function () {
        let reference = _getReferenceAncestor(this);
        let state = Pane.State.build();
        if (state.isLoaded(reference.dataset.contentKey)) {
            return;
        }
        _loadContent(reference, true);
    });
    _onClick("binaryupdate", function () {
        let reference = _getReferenceAncestor(this);
        Transformation.Overlay.showBinaryUpdate(reference.dataset.templateKey, reference.dataset.contentPath);
        return false;
    });
    
    function _onClick(actionName, clickFunction) {
        $list.on("click", $$.toCssSelector({action: actionName}), clickFunction);
    }
    
    function _getReferenceAncestor(element) {
        return  Bdf.getMandatoryAncestor(element, {role: "content-reference"});
    }

    
    function _getTransformationKey(element) {
        if (element.dataset.role === "transformation") {
            return element.dataset.transformationKey;
        }
        return Bdf.getMandatoryAncestor(element, {role: "transformation"}).dataset.transformationKey;
    }
    
    function _getTemplateKey(element) {
        if (element.dataset.role === "template") {
            return element.dataset.templateKey;
        }
        return Bdf.getMandatoryAncestor(element, {role: "template"}).dataset.templateKey;
    }
    
    function _loadContent(reference, isInStock) {
        let overlayId = Bdf.Overlay.startRunning();
        Bdf.Ajax.loadTemplateContent(reference.dataset.templateKey, reference.dataset.contentPath, function (templateContent) {
            Transformation.ContentForm.load(templateContent, isInStock);
            Overlay.end(overlayId);
        });
    }
};

Transformation.List.checkTransformationState = function ($transformation) {
    var stateObject = {state: Transformation.EMPTY_STATE};
    var $templateArray = $$($transformation, {role: "template"});
    for(let i = 0; i < $templateArray.length; i++) {
        var $template = $($templateArray[i]);
        var state = $template.data("templateState");
         if (state === "ok") {
            _checkState(Transformation.OK_STATE);
        } else if (state === "with_warnings") {
             _checkState(Transformation.WARNING_STATE);
        } else {
             _checkState(Transformation.ERROR_STATE);
        }
    }
    Pane.updateStateClass($$($transformation, {role: "transformation-title"}), _toClass());
    if (stateObject.state === Transformation.EMPTY_STATE) {
        $transformation.addClass("transformation-Empty");
    } else {
        $transformation.removeClass("transformation-Empty");
    }

    function _checkState(newState) {
        if (newState > stateObject.state) {
            stateObject.state = newState;
        }
    }
    
    function _toClass() {
        switch(stateObject.state) {
            case Transformation.EMPTY_STATE :
                return "transformation-state-Empty";
            case Transformation.OK_STATE :
                return "transformation-state-Ok";
            case Transformation.WARNING_STATE :
                return "transformation-state-Warning";
            case Transformation.ERROR_STATE :
                return "transformation-state-Error";
        }
    }
};

Transformation.List.update = function (templateDescription) {
    var $template = $$({role: "template", templateKey: templateDescription.key});
    $$($template, {role: "template-title"}).html(templateDescription.title);
    $$($template, {action: "extractionreinit"}).toggleClass("hidden", !Transformation.withExtractionReinit(templateDescription));
    $$($template, {role: "template-body"}).html(Bdf.render("transformation:list/template_body", templateDescription));
    $template.data("templateState", templateDescription.state);
    Pane.updateStateClass($template, "transformation-templatestate-" + templateDescription.state);
    Pane.checkState();
    Transformation.List.checkTransformationState($$({role: "transformation", transformationKey: templateDescription.transformationKey}));
};

Transformation.List.insert = function (templateDescription) {
    var templateKey = templateDescription.key;
    var transformationKey = templateDescription.transformationKey;
    var $transformation = $$({role: "transformation", transformationKey: transformationKey});
    if ($transformation.length === 0) {
        return;
    }
    var newHtml = Bdf.render("transformation:list/template", templateDescription);
    if (templateDescription.extension) {
        var $extension = $$($transformation, {role: "extension", extension: templateDescription.extension});
        if ($extension.length > 0) {
            _insertInList($$($extension, {role: "extension-template-list"}));
        } else {
            newHtml = Bdf.render("transformation:list/extensionwrap", {
                extension: templateDescription.extension,
                content: newHtml
            });
            var $extensionList = $$($transformation, {role: "extension"});
            var done = false;
            for(let i = 0; i < $extensionList.length; i++) {
                let otherExtension = $extensionList[i];
                if (otherExtension.dataset.extension > templateDescription.extension) {
                    $(otherExtension).before($extension);
                    done = true;
                    break;
                }
            }
            if (!done) {
                $$($transformation, {role: "template-list-area"}).append(newHtml);
            }
        }
    } else {
        _insertInList($$($transformation, {role: "simple-template-list"}));
    }
    Bdf.Deploy.init($transformation);
    Bdf.Deploy.ensureLinkVisibility($$($transformation, {role: "template", templateKey: templateKey}), true);
    Pane.checkState();
    Transformation.List.checkTransformationState($transformation);
    
    
    function _insertInList($templateList) {
        var $templateArray =  $$($templateList, {role: "template"});
        var done = false;
        for(let i = 0; i < $templateArray.length; i++) {
            let otherTemplate = $templateArray[i];
            if (otherTemplate.dataset.templateKey > templateKey) {
                $(otherTemplate).before(newHtml);
                done = true;
                break;
            }
        }
        if (!done) {
            $templateList.append(newHtml);
        }
    }
};

Transformation.List.remove = function (templateKey) {
    var $template = $$({role: "template", templateKey:templateKey});
    var transformationKey = Transformation.split(templateKey).transformationKey;
    var $extension = $template.parents($$.toCssSelector({role: "extension"}));
    $template.remove();
    if ($extension.length === 1) {
        var $templates = $$($extension, {role: "template"});
        if ($templates.length === 0) {
            $extension.remove();
        }
    }
    Transformation.List.checkTransformationState($$({role: "transformation", transformationKey: transformationKey}));
};
