#include colour.js
#include common.js
#include utility.js
#include colpick/picker.jsx
#include ui/input-menus.js
#include ui/markup.js
#include ui/view.js

Umi.UI.Markup = (function() {
    const insertRaw = function(start, end) {
        const selectionLength = Umi.UI.View.GetSelectionLength();
        Umi.UI.View.EnterAtCursor(start);
        Umi.UI.View.SetPosition(Umi.UI.View.GetPosition() + selectionLength + start.length);
        Umi.UI.View.EnterAtCursor(end);
        Umi.UI.View.SetPosition(Umi.UI.View.GetPosition() - selectionLength);
        Umi.UI.View.SetPosition(Umi.UI.View.GetPosition() + selectionLength, true);
        Umi.UI.View.Focus();
    };

    const pickerTarget = document.body;
    let picker, pickerVisible = false;

    const insert = function(ev) {
        if(this.dataset.umiTagName === 'color' && !pickerVisible) {
            pickerVisible = true;

            if(picker === undefined)
                picker = new MamiColourPicker({
                    presets: futami.get('colours'),
                });

            pickerTarget.appendChild(picker.getElement());

            picker.dialog(picker.suggestPosition(ev))
                .then(colour => insertRaw(`[color=${MamiColour.hex(colour)}]`, '[/color]'))
                .finally(() => pickerVisible = false);
        } else
            insertRaw(
                this.dataset.umiBeforeCursor,
                this.dataset.umiAfterCursor
            );
    };

    return {
        Add: function(name, text, beforeCursor, afterCursor) {
            Umi.UI.InputMenus.Get('markup').appendChild($e({
                tag: 'button',
                attrs: {
                    type: 'button',
                    id: 'umi-msg-menu-markup-btn-' + name,
                    classList: ['markup__button', 'markup__button--' + name],
                    dataset: {
                        umiTagName: name,
                        umiBeforeCursor: beforeCursor,
                        umiAfterCursor: afterCursor,
                    },
                    onclick: insert,
                },
                child: text,
            }));
        },
        Reset: function() {
            Umi.UI.InputMenus.Get('markup').innerHTML = '';
        },
        Insert: insert,
        InsertRaw: insertRaw,
    };
})();
