/* global Bdf,$$,SelectionDef,Pane */

SelectionDef.List = {};

SelectionDef.List.init = function (callback) {
    Bdf.Ajax.loadSelectionDefArray(function (selectionDefArray) {
        selectionDefArray = SelectionDef.initArray(selectionDefArray);
        let $listBody = $$("listpane_body");
        $listBody.html(Bdf.render("selectiondef:list/selectiondef", selectionDefArray));
        Bdf.Deploy.init($listBody);
        SelectionDef.List.initActions();
        if (callback) {
            callback();
        }
    });
};

SelectionDef.List.initActions = function () {
    $$("listpane_button_newselectiondef").click(SelectionDef.Overlay.showCreationForm);
    var $body = $$("listpane_body");
    _onClick("form", function () {
        if (!Bdf.confirmUnload()) {
            return false;
        }
        let name = Pane.getEntryName(this);
        Pane.loadOrDestock(name, function () {
            SelectionDef.Form.load(name);
        });
    });
    _onClick("remove", function () {
        SelectionDef.Overlay.showRemoveConfirm(Pane.getEntryName(this));
    });
    
    function _onClick(actionName, clickFunction) {
        $body.on("click", $$.toCssSelector({action: actionName}), clickFunction);
    }
};

SelectionDef.List.updateSelectionDef = function (newSelectionDef) {
    var $currentSelectionDef =  $$({role: "entry", name: newSelectionDef.name});
    $$($currentSelectionDef, {role: "entry-title"}).html(newSelectionDef.title);
};
