/* global Bdf,MultiAdmin,Overlay,$,$$ */

MultiAdmin.PersonManager = {};

MultiAdmin.PersonManager.load = function () {
    var managerId = Bdf.generateId();
    $$("layout_main").html(Bdf.render("multiadmin:personmanager/pane", {
        managerId: managerId
    }));
    $$(managerId, "searchform").ajaxForm({
        dataType: "json",
        success: function (data, textStatus, jqXHR, $form) {
            if ((MultiAdmin.testAuthentification(data)) && (Bdf.checkError(data))) {
                $$(managerId, "body").addClass("multi-personmanager-Active");
                _loadPerson(data.person);
                _loadCommands(data.person);
            }
       }
    });


    function _loadPerson(person) {
        _completePerson(person);
        $$(managerId, "person").html(Bdf.render("multiadmin:personmanager/person", {
            managerId: managerId,
            person: person
        }));
    }
     
    function _loadCommands(person) {
         $$(managerId, "person").html(Bdf.render("multiadmin:personmanager/person", {
            managerId: managerId,
            person: person
        }));
        $$(managerId, "changeformarea").html(Bdf.render("multiadmin:personmanager/changeform", {
            managerId: managerId,
            person: person
        }));
        let candidateArray = _getCandidateFichothequeArray(person);
        if (candidateArray.length > 0) {
            $$(managerId, "addformarea").html(Bdf.render("multiadmin:personmanager/addform", {
                managerId: managerId,
                person: person,
                candidateArray: candidateArray
            }));
        } else {
            $$(managerId, "addformarea").html("");
        }
        $$(managerId, "changeform").ajaxForm({
            dataType: "json",
            beforeSubmit: function (arr, $form, options) {
                if (!_testFichothequeSelection($form)) {
                    return false;
                }
                let selectElement = $$.one(managerId, "changeform", "type");
                if (selectElement.options[selectElement.selectedIndex].value === "none") {
                    return false;
                } else {
                    return true;
                }
            },
            success: function (data, textStatus, jqXHR, $form) {
                _updateData(data);
           }
        });
        $$(managerId, "changeform", "type").change(function () {
            let type = this.options[this.selectedIndex].value;
            if (type === "none") {
                 $$(managerId, "changeform", "submit").addClass("hidden");
            } else {
                $$(managerId, "changeform", "submit").removeClass("hidden");
            }
            let $manager = $$(managerId, "changeform");
            $$($manager, {role: "type"}).addClass("hidden");
            $$($manager, {role: "type", type: type}).removeClass("hidden");
        });
        $$(managerId, "addform").ajaxForm({
            dataType: "json",
            beforeSubmit: function (arr, $form, options) {
                return _testFichothequeSelection($form);
            },
            success: function (data, textStatus, jqXHR, $form) {
                _updateData(data);
           }
        });
        Bdf.Deploy.init($$(managerId, "changeformarea"));
        Bdf.Deploy.init($$(managerId, "addformarea"));
     }
     
    function _completePerson(person) {
        var withSpecificName = false;
        for(let status of person.statusArray) {
            status._levelLetter = _getLevelLetter(status.level);
            if (status.hasOwnProperty("specificName")) {
                withSpecificName = true;
            }
        }
        person._withSpecificName = withSpecificName;
    }
    
    function _getLevelLetter(level) {
        switch(level) {
            case "admin":
                return "A";
            case "user":
                return "B";
            case "readonly":
                return "C";
            case "inactive":
                return "D";
            default:
                return "F";
        }
    }
    
    function _getCandidateFichothequeArray(person) {
        let personSphereName = person.sphereName;
        let existingArray = new Array();
        let candidateArray = new Array();
        for(let status of person.statusArray) {
            existingArray.push(status.fichothequeName);
        }
        for(let fichotheque of MultiAdmin.fichothequeArray) {
            if ((fichotheque.init) && (__hasSphere(fichotheque))) {
                if (existingArray.indexOf(fichotheque.name) === -1) {
                    candidateArray.push(fichotheque);
                }
            }
        }
        return candidateArray;
        
        function __hasSphere(fichotheque) {
            for(let node of fichotheque.sphere) {
                if (__testNode(node)) {
                    return true;
                }
            }
            return false;
        }
        
        function __testNode(node) {
            if (node.node === "subset") {
                return (node.name === personSphereName);
            } else {
                for(let subnode of node.array) {
                    if (__testNode(subnode)) {
                        return true;
                    }
                }
                return false;
            }
        }
    }
    
    function _updateData(data) {
        if ((MultiAdmin.testAuthentification(data)) && (Bdf.checkError(data))) {
            _loadPerson(data.person);
            if ((data.commandMessage) && (data.commandMessage.type === "done")) {
                let $message = $$(managerId, "donemessage");
                $message.text(data.commandMessage.text).removeClass("hidden");
                window.setTimeout(function () {
                    $message.addClass("hidden");
                }, 5000);
            }
            $$(managerId, "body").scrollTop(0);
        }
    }
    
    function _testFichothequeSelection($form) {
        let $checkedTarget = $$($form, {_name: "target", _checked: true});
        if ($checkedTarget.val() === "selection") {
            let $checkedFichotheques = $$($form, {_name: "fichotheques", _checked: true});
            if ($checkedFichotheques.length > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }
     
};

