#include utility.js
#include ui/input-menus.js

Umi.UI.InputMenus = (function() {
    const ids = [];
    let current = '';

    const inputMenuActive = 'input__menu--active';
    const inputButtonActive = 'input__button--active';

    const createButtonId = id => `umi-msg-menu-btn-${id}`;

    const toggle = function(baseId) {
        const button = createButtonId(baseId);
        const menu = 'umi-msg-menu-sub-' + baseId;

        if($c(inputMenuActive).length)
            $c(inputMenuActive)[0].classList.remove(inputMenuActive);

        if($c(inputButtonActive).length)
            $c(inputButtonActive)[0].classList.remove(inputButtonActive);

        if(current !== baseId) {
            $i(menu).classList.add(inputMenuActive);
            $i(button).classList.add(inputButtonActive);
            current = baseId;
        } else current = '';
    };

    const createButton = function(id, title, onClick) {
        return $e({
            tag: 'button',
            attrs: {
                type: 'button',
                id: createButtonId(id),
                classList: ['input__button', 'input__button--' + id],
                title: title,
                onclick: onClick || (function() {
                    toggle(id);
                }),
            },
        });
    };

    return {
        Add: function(baseId, title, beforeButtonId) {
            if(ids.includes(baseId))
                return;
            ids.push(baseId);

            let beforeButton;
            if(typeof beforeButtonId === 'string')
                beforeButton = $i(createButtonId(beforeButtonId))
            if(!(beforeButton instanceof Element))
                beforeButton = $i('umi-msg-send');

            $i('umi-msg-container').insertBefore(createButton(baseId, title), beforeButton);
            $i('umi-msg-menu').appendChild(
                $e({ attrs: { 'class': ['input__menu', 'input__menu--' + baseId], id: 'umi-msg-menu-sub-' + baseId } })
            );
        },
        AddButton: function(baseId, title, onClick, beforeButtonId) {
            if(ids.includes(baseId))
                return;
            ids.push(baseId);

            let beforeButton;
            if(typeof beforeButtonId === 'string')
                beforeButton = $i(createButtonId(beforeButtonId))
            if(!(beforeButton instanceof Element))
                beforeButton = $i('umi-msg-send');

            $i('umi-msg-container').insertBefore(createButton(baseId, title, onClick), beforeButton);
        },
        Get: function(baseId, button) {
            const id = 'umi-msg-menu-' + (button ? 'btn' : 'sub') + '-' + baseId;
            if(ids.indexOf(baseId) >= 0)
                return $i(id);
            return null;
        },
        Remove: function(baseId) {
            $ri(createButtonId(baseId));
            $ri('umi-msg-menu-sub-' + baseId);
        },
        Toggle: toggle,
        CreateButton: createButton,
    };
})();
