#include utility.js

const MszShowConfirmBox = async (text, title, target) => {
    let result = false;

    await MszShowMessageBox(text, title, [
        { text: 'Yes', callback: async () => result = true },
        { text: 'No' },
    ], target);

    return result;
};

const MszShowMessageBox = (text, title, buttons, target) => {
    if(typeof text !== 'string') {
        if(text !== undefined && text !== null && typeof text.toString === 'function')
            text = text.toString();
        else throw 'text must be a string';
    }
    if(!(target instanceof Element))
        target = document.body;

    if(typeof title !== 'string')
        title = 'Information';
    if(!Array.isArray(buttons))
        buttons = [];

    return new Promise((resolve, reject) => {
        if(target.querySelector('.messagebox')) {
            reject();
            return;
        }

        let buttonsElem;
        const html = <div class="messagebox">
            <div class="container messagebox__container">
                <div class="container__title">
                    <div class="container__title__background"/>
                    <div class="container__title__text">{title}</div>
                </div>
                <div class="container__content">{text}</div>
                {buttonsElem = <div class="messagebox__buttons"/>}
            </div>
        </div>;

        let firstButton;
        if(buttons.length < 1) {
            firstButton = <button class="input__button" onclick={() => {
                html.remove();
                resolve();
            }}>OK</button>;
            buttonsElem.appendChild(firstButton);
        } else {
            for(const button of buttons) {
                const buttonElem = <button class="input__button" onclick={() => {
                    html.remove();

                    if(typeof button.callback === 'function')
                        button.callback().finally(() => resolve());
                    else
                        resolve();
                }}>{button.text}</button>;
                buttonsElem.appendChild(buttonElem);

                if(firstButton === undefined)
                    firstButton = buttonElem;
            }
        }

        target.appendChild(html);
        firstButton.focus();
    });
};
