/* global Bdf,$$,Role,CodeMirror,Pane */

Role.Form = {};

Role.Form.load = function (roleName) {
    var role = Role.getRole(roleName);
    if (!role) {
        return;
    }
    var isInStock = false;
    var formId = Bdf.generateId();
    $$("layout_main").html(Bdf.render("role:form", {
        action: Bdf.URL + "administration",
        formId: formId,
        roleName: role.name,
        title: role.title,
        labelArray: Bdf.toLabelArray(role.labelMap),
        labelsLocKey: "_ title.administration.rolelabels",
        corpusHidden: _hide("corpus"),
        thesaurusHidden: _hide("thesaurus"),
        sphereHidden: _hide("sphere"),
        addendaHidden: _hide("addenda"),
        albumHidden: _hide("album"),
        corpusTree: Role.Form.convertCorpusTree(role),
        thesaurusTree: Role.Form.convertTree(role, "thesaurus"),
        sphereTree: Role.Form.convertTree(role, "sphere"),
        addendaTree: Role.Form.convertTree(role, "addenda"),
        albumTree: Role.Form.convertTree(role, "album"),
        attributes: Bdf.attrMapToString(role.attrMap),
        attributesLocKey: "_ title.administration.roleattributes",
        commandKey: "ROL-02",
        commandUrl: Bdf.getCommandUrl("ROL-02")
    }));
    $$(formId).ajaxForm({
        beforeSerialize: function ($form, options) {
            if (isInStock) {
                return false;
            } else {
                attributesCodeMirror.save();
                return true;
            }
        },
        dataType: "json",
        success: function (data, textStatus, jqXHR, $form) {
            if (Bdf.checkError(data)) {
                Pane.setChange(false);
                if (Bdf.showCommandMessage(data.commandMessage)) {
                    Bdf.updateDefaultValues($$(formId));
                    let newRole = Role.updateRole(data.role);
                    $$(formId, {role: "metadata-title"}).html(newRole.title);
                }
            }
        }
    });
    $$(formId, "button_stock").click(function () {
        Pane.moveMainToStock();
    });
    var attributesCodeMirror = Pane.initAttributesDetails(formId);
    Bdf.Deploy.init($$("layout_main"));
    $$(formId).data("stockHandler", _stockHandler);
    Pane.checkState();
    Pane.checkTooltip($$(formId));
    
    function _hide(subsetCategory) {
        for(var prop in role.permissionMap) {
            if (prop.startsWith(subsetCategory)) {
                return false;
            }
        }
        return true;
    }
    
    function _stockHandler(stock) {
        isInStock = stock;
        attributesCodeMirror.setOption("readOnly", stock);
        Pane.setReadOnly($$(formId), stock);
    }

};

Role.Form.convertCorpusTree = function (role) {
    var subsetCategory = "corpus";
    var permissionMap = role.permissionMap;
    var withNoneOption = (role.name === "_default");
    return _readNodeArray(Role.subsetTrees.getTree(subsetCategory));
    
    
    function _readNodeArray(nodeArray) {
        var resultArray = new Array();
        for(var i = 0, len = nodeArray.length; i < len; i++) {
            var node = nodeArray[i];
            var resultItem = {
                node:  node.node,
                name: node.name,
                title: node.title,
                generatedId: Bdf.generateId() 
            };
            if (node.node === "subset") {
                resultItem.subsetKey = subsetCategory + "_" + node.name;
                resultItem.subsetCategory = subsetCategory;
                resultItem.subsetName = node.name;
                var permission;
                if (permissionMap.hasOwnProperty(resultItem.subsetKey)) {
                    resultItem.checked = true;
                    permission = permissionMap[resultItem.subsetKey];
                    resultItem.currentLevel = permission.level;
                } else {
                    resultItem.checked = false;
                    resultItem.currentLevel = "standard";
                    permission = {
                        level: "standard"
                    };
                }
                if (permission.level !== "custom") {
                    permission.create = true;
                    permission.read = "all";
                    permission.write = "own";
                }
                resultItem.permission = permission;
                resultItem.withNoneOption = withNoneOption;
            } else if (node.node === "group") {
                resultItem.hidden = !Role.Form.containsPermission(node, permissionMap, subsetCategory);
                resultItem.items =  _readNodeArray(node.array);
            }
            resultArray.push(resultItem);
        }
        return resultArray;
     }

};

Role.Form.convertTree = function (role, subsetCategory) {
    var permissionMap = role.permissionMap;
    var withNoneOption = (role.name === "_default");
    return _readNodeArray(Role.subsetTrees.getTree(subsetCategory));
    
    
    function _readNodeArray(nodeArray) {
        var resultArray = new Array();
        for(var i = 0, len = nodeArray.length; i < len; i++) {
            var node = nodeArray[i];
            var resultItem = {
                node:  node.node,
                name: node.name,
                title: node.title,
                generatedId: Bdf.generateId() 
            };
            if (node.node === "subset") {
                resultItem.subsetKey = subsetCategory + "_" + node.name;
                resultItem.subsetCategory = subsetCategory;
                resultItem.subsetName = node.name;
                if (permissionMap.hasOwnProperty(resultItem.subsetKey)) {
                    resultItem.checked = true;
                    var permission = permissionMap[resultItem.subsetKey];
                    resultItem.currentLevel = permission.level;
                } else {
                    resultItem.checked = false;
                    resultItem.currentLevel = "standard";
                }
                resultItem.withNoneOption = withNoneOption;
            } else if (node.node === "group") {
                resultItem.hidden = !Role.Form.containsPermission(node, permissionMap, subsetCategory);
                resultItem.items =  _readNodeArray(node.array);
            }
            resultArray.push(resultItem);
        }
        return resultArray;
     }

};

Role.Form.containsPermission = function(groupNode, permissionMap, subsetCategory) {
    var length = groupNode.array.length;
    for(var i = 0; i < length; i++) {
        var node = groupNode.array[i];
        if (node.node === "subset") {
            if (permissionMap.hasOwnProperty(subsetCategory + "_" + node.name)) {
                return true;
            }
        } else if (node.node === "group") {
            var subgroupResult = Role.Form.containsPermission(node, permissionMap, subsetCategory);
            if (subgroupResult) {
                return true;
            }
        }
    }
    return false;
};