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

Pioche.ARGS = {
  callKey: "", 
  limit: -1,
  count: -1,
  separator: "",
  wanted: "",
  json: "",
  buttons: {},
  hiddenValues: []
};

Pioche.JSONITEM_MAP = new Map();

Pioche.init = function (args) {
    var piocheId = Bdf.generateId();
    var jsonData = null;
    $$(args.clientId).html(Bdf.render("pioche:client", {
        args: args,
        piocheId: piocheId
    }));
    $$(piocheId, "confirm").click(_updateCaller);
    $$(piocheId, "cancel").click(function () {
        window.close();
    });
    $$(piocheId, "fichecreation").click(function () {
        _openFicheCreation();
    });
    $$(piocheId, "select", "available").click(function () {
        _selection(this);
    }).keydown(function (event) {
         if (event.key === "Enter") {
            _selection(this);
        }
    });
    $$(piocheId, "select", "selected").click(function () {
        _deselection(this);
    }).keydown(function (event) {
         if (event.key === "Enter") {
            _deselection(this);
        }
    });
    if (args.limit === 1) {
        $$(piocheId, "select", "selected").attr("size", "2");
    }
    if ((args.count > -1) && (args.count < 31)) {
        $$(piocheId, "header").addClass("hidden");
        $$(piocheId, "form").ajaxSubmit({
            dataType:  'json',
            success:   _processJson
        });
    } else {
        $$(piocheId, "form").ajaxForm({
            dataType:  'json',
            beforeSubmit: function () {
                $$(piocheId, "tabs", "available").empty();
            },
            success:   function (data, textStatus, jqXHR, $form) {
                _processJson(data);
            }
        });
        $$(piocheId, "qinput").focus();
    }
    Bdf.Shortcut.init();
    
    function _updateCaller() {
        this.disabled = true;
        let callback = window.opener.Bdf.getCallback(args.callKey);
        if (callback) {
            let selectionArray = new Array();
            $$(piocheId, "select", "selected").find("option").each(function (index, option) {
                let jsonItem = Pioche.JSONITEM_MAP.get(option.value);
                 if (jsonItem) {
                    selectionArray.push(jsonItem);
                }
            });
            callback(selectionArray);
        } else {
            _defaultCallerUpdate();
        }
        window.close();
    }
    
    function _defaultCallerUpdate() {
        let limit = args.limit;
        let newValue = "";
        $$(piocheId, "select", "selected").find("option").each(function (index, option) {
            newValue = newValue + option.value;
            if (limit !== 1) newValue = newValue + "; ";
        });               
        let element = window.opener.document.getElementById(args.callKey);
        if (limit !== 1) {
            Bdf.appendValue(element, newValue);
        } else {
            element.value = newValue;
        }
        element.selectionStart = element.value.length;
        element.focus();
    }
    
    function _openFicheCreation() {
        if ((window.opener.Ficheform) && (window.opener.Ficheform.CorpusInclude)) {
            window.opener.Ficheform.CorpusInclude.showFicheCreation(args.callKey);
        }
        window.close();
    }

    function _processJson(data) {
        jsonData = data;
        for(let jsonItem of jsonData.array) {
            let keyAndText = _getKeyAndText(jsonItem);
            Pioche.JSONITEM_MAP.set(keyAndText.key, jsonItem);
        }
        let itemCount = data.count;
        $$(piocheId, "count", "available").text(itemCount);
        let $tabs = $$(piocheId, "tabs", "available").empty();
        if (itemCount === 0) {
            $tabs.addClass("pioche-Empty");
            $tabs.text(Bdf.Loc.get("_ warning.pioche.emptyresult"));
            _updateAvailable(0);
        } else {
            $tabs.removeClass("pioche-Empty");
            let seuilvisibilite = Math.ceil(itemCount/10);
            if (seuilvisibilite > 1) {
                for (let k = 0; k < seuilvisibilite;k++) {
                   $tabs.append(Bdf.render("pioche:tab", {
                       piocheId: piocheId,
                       number: k,
                       disabled: (k === 0)
                   }));
                   $$(piocheId, "tab", k).click(function () {
                       _activeTab(k, $(this));
                   });
                }
                _activeTab(0, $$(piocheId, "tab", 0));
            } else {
                _updateAvailable(0);
            }
        }
    }

    function _activeTab(dizaine, $tab) {
        $$({role: "tab"}).prop("disabled", false);
        $tab.prop("disabled", true);
        _updateAvailable(dizaine);
    }

    function _updateAvailable(dizaine) {
        let $avalaibleSelect = $$(piocheId, "select", "available").empty();
        let plafond = Math.min(jsonData.count, 10*(dizaine + 1));
        let plancher = 10*dizaine;
        for (let k = plancher; k < plafond;k ++) {
            let keyAndText = _getKeyAndText(jsonData.array[k]);
            $avalaibleSelect.append(Bdf.render("pioche:option", {
                value: keyAndText.key,
                text: keyAndText.text
            }));
        }
    }

    function _selection(select) {
        let idx = select.selectedIndex;
        if (idx === -1) return;
        let option = select.options[idx];
        let value = option.value;
        let $selectedSelect = $$(piocheId, "select", "selected");
        for (let opt of $selectedSelect[0].options) {
            if (opt.value === value) return;
        }
        $selectedSelect.append(Bdf.render("pioche:option", {
            value: value,
            text: option.text
        }));
        _checkSelect();
    }

    function _checkSelect() {
        let count = $$(piocheId, "select", "selected").find("option").length;
        let limit = args.limit;
        if((limit !== -1) && (count >= limit)) {
            $$(piocheId, "select", "available").prop("disabled", true);
        }
        else {
            $$(piocheId, "select", "available").prop("disabled", false);
        }
        $$(piocheId, "confirm").prop("disabled", (count === 0));
        $$(piocheId, "count", "selected").text(count);
    }

    function _deselection(select) {
        let idx = select.selectedIndex;
        if (idx === -1) return;
        select.remove(idx);
        select.selectedIndex = -1;
        _checkSelect();
    }
    
    function _getKeyAndText(jsonItem) {
        let key = "";
        let text = "";
        switch(args.wanted) {
            case "id":
                key = jsonItem.id;
                if (jsonItem.code) {
                    text = jsonItem.code;
                } else {
                    text = "" + key;
                }
                break;
            case "code-id":
                if (jsonItem.code) {
                    key = jsonItem.code;
                } else {
                    key = jsonItem.id;
                }
                text = "" + key;
                break;
            case "code-title":
                 if (jsonItem.code) {
                    key = jsonItem.code;
                    text = "" + key;
                } else if (jsonItem.title) {
                    key = jsonItem.title;
                    text = "";
                } else {
                    key = jsonItem.id;
                    text = "" + key;
                }
                break;
        }
        if (jsonItem.title) {
            if (text) {
                text = text + args.separator + jsonItem.title;
            } else {
                text = jsonItem.title;
            }
        }
        if (jsonItem.description) {
            text = text + " (" + jsonItem.description + ")";
        }
        return {
            key: key.toString(),
            text: text
        };
    }
};

$(function () {
    Bdf.initTemplates();
    Pioche.init(Pioche.ARGS);
});
