/* global Bdf,$$,Pane */
/**
 * Objet global définissant l'espace de nom Role
 * 
 * @namespace Role
 */
var Role = {};

Role.subsetTrees = null;
Role.array = null;


/******************************************************************************
 * Actions sur Role
 ******************************************************************************/

Role.initArray = function (array) {
    for(let roleObj of array) {
        Role.completeRole(roleObj);
    }
    Role.array = array;
    return array;
};

Role.getRole = function (roleName) {
    for(let role of Role.array) {
        if (role.name === roleName) {
            return role;
        }
    }
    return null;
};

Role.updateRole = function (newRole) {
    newRole = Role.completeRole(newRole);
    Bdf.updateInArray(Role.array, newRole);
    Role.List.updateRole(newRole);
    return newRole;
};

Role.removeRole = function (name) {
    Bdf.removeInArray(Role.array, name);
    Pane.removeContents(name);
    Pane.removeEntry($$("listpane_body"), name);
};

Role.insertRole = function (role) {
    role = Role.completeRole(role);
    Bdf.insertInArray(Role.array, role);
    var $entry = Pane.insertEntry($$("listpane_body"), role.name, Bdf.render("role:list/role", role));
    $$("listpane_body").animate({
        scrollTop: $entry.offset().top
    }, 1000, function () {
        Bdf.Deploy.ensureLinkVisibility($entry, true);
    });
    Role.Form.load(role.name);
    return role;
};

Role.completeRole = function (roleObj) {
    var roleName = roleObj.name;
    return roleObj;
};


/******************************************************************************
 * Enregistrement de fonction
 ******************************************************************************/

Pane.registerCheckFunction(function (state) {
    $(".pane-list-ActiveItem").removeClass("pane-list-ActiveItem");
    if (state.withMain()) {
        let $role = $$({role: "entry", name: state.mainContentKey});
        $$($role, {role: "entry-header"}).addClass("pane-list-ActiveItem");
    }
});


/******************************************************************************
 * Initialisation
 ******************************************************************************/

$(function () { 
    Bdf.initTemplates();
    Pane.initLayout();
    $$("layout_list").html(Bdf.render("role:list/pane", {}));
    Bdf.initBeforeUnload();
    Bdf.runSerialFunctions(
        Bdf.Ajax.initLangConfiguration,
        _initSubsetTrees,
        Role.List.init
    );
    Pane.initShortcuts();
    
    
    function _initSubsetTrees(callback) {
        Bdf.SubsetTrees.load(function (subsetTrees) {
            Role.subsetTrees = subsetTrees;
            if (callback) {
                callback();
            }
        });
    }
    
});