/* global Bdf,$$ */

Bdf.CommandVeil = {};

Bdf.CommandVeil.CURRENT_ID = "";

Bdf.CommandVeil.init = function () {
    $$({veilRole: "unit"}).each( function (index, element) {
        _initUnit(element);
    });
    $(window).on('keydown.submit', function (event) {
        if (_testSubmit(event)) {
            event.preventDefault();
            event.stopPropagation();
            if (Bdf.CommandVeil.CURRENT_ID) {
                let submitButtons = $$(Bdf.CommandVeil.CURRENT_ID).find("button[type=submit]");
                if (submitButtons.length > 0) {
                    $(submitButtons[0]).click();
                }
            }
        }
    });
    
    function _initUnit(element) {
        let $element = $(element);
        if (!element.id) {
            element.id = Bdf.generateId();
        }
        $element.on("focus", "*", function () {
            Bdf.CommandVeil.unveil(element);
        });
    }
    
    function _testSubmit(keyEvent) {
        switch(keyEvent.key) {
            case "s":
            case "S":
                return __withMod();
            default:
                return false;

        }
        
        function __withMod() {
            if ((!keyEvent.shiftKey) && (!keyEvent.altKey)) {
                if (Bdf.MAC_PLATFORM) {
                    return (keyEvent.metaKey);
                } else {
                    return (keyEvent.ctrlKey);
                }
            } else {
                return false;
            }
        }
    }
};

Bdf.CommandVeil.unveil = function (element) {
    $$(element, {veilRole: 'veil'}).remove();
    $(element).removeClass("unit-Veiled");
    if (Bdf.CommandVeil.CURRENT_ID !== element.id) {
        Bdf.CommandVeil.CURRENT_ID = element.id;
         _veilOthers();
    }
    
    function _veilOthers() {
        $$({veilRole: "unit"}).each( function (index, el) {
            if (el.id !== Bdf.CommandVeil.CURRENT_ID) {
                Bdf.CommandVeil.veil(el);
            }
       });
    }
};

Bdf.CommandVeil.veil = function (element) {
    if ($$(element, {veilRole: 'veil'}).length === 0) {
        $(element).addClass("unit-Veiled");
        $("<div class='unit-Veil' data-veil-role='veil'></div>").appendTo($(element)).click(function () {
            Bdf.CommandVeil.unveil(element);
        });
    }
 };

$(function () {
    Bdf.CommandVeil.init();    
});
