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

Umi.UI.Emoticons = (function() {
    return {
        Init: function() {
            const menu = Umi.UI.InputMenus.Get('emotes');
            menu.innerHTML = '';

            MamiEmotes.forEach(Umi.User.getCurrentUser().perms.rank, function(emote) {
                menu.appendChild($e({
                    tag: 'button',
                    attrs: {
                        type: 'button',
                        className: 'emoticon emoticon--button',
                        title: emote.strings[0],
                        dataset: {
                            umiEmoticon: ':' + emote.strings[0] + ':',
                        },
                        onclick: 'Umi.UI.Emoticons.Insert(this)',
                    },
                    child: {
                        tag: 'img',
                        attrs: {
                            className: 'emoticon',
                            src: emote.url,
                            alt: emote.strings[0],
                        },
                    }
                }));
            });
        },
        Parse: function(element, message) {
            if(!mami.settings.get('enableEmoticons'))
                return element;

            let inner = element.innerHTML;

            MamiEmotes.forEach(message.getUserV2().perms.rank, function(emote) {
                const image = $e({
                    tag: 'img',
                    attrs: {
                        className: 'emoticon',
                        src: emote.url,
                    },
                });

                for (const i in emote.strings) {
                    const trigger = ':' + emote.strings[i] + ':',
                        match = new RegExp(trigger, 'g');
                    image.alt = trigger;
                    inner = inner.replace(match, image.outerHTML);
                }
            });

            element.innerHTML = inner;

            return element;
        },
        Insert: function(sender) {
            const emoticon = sender.getAttribute('data-umi-emoticon');
            Umi.UI.View.EnterAtCursor(sender.getAttribute('data-umi-emoticon'));
            Umi.UI.View.SetPosition(Umi.UI.View.GetPosition() + emoticon.length);
            Umi.UI.View.SetPosition(Umi.UI.View.GetPosition(), true);
            Umi.UI.View.Focus();
        },
    };
})();
