#include utility.js
#include embed/embed.js
#include events/christmas2019.js
#include events/events.js
#include ext/sakuya.js
#include forum/editor.jsx
#include messages/messages.js

(async () => {
    const initLoginPage = async () => {
        const forms = Array.from($qa('.js-login-form'));
        if(forms.length < 1)
            return;

        const updateForm = async (avatar, userName) => {
            if(!(avatar instanceof Element) || !(userName instanceof Element))
                return;

            const result = (await $x.get(`/auth/login.php?resolve=1&name=${encodeURIComponent(userName.value)}`, { type: 'json' })).body();

            avatar.src = result.avatar;
            if(result.name.length > 0)
                userName.value = result.name;
        };

        for(const form of forms) {
            const avatar = form.querySelector('.js-login-avatar');
            const userName = form.querySelector('.js-login-username');
            let timeOut;

            await updateForm(avatar, userName);

            userName.addEventListener('input', function() {
                if(timeOut !== undefined)
                    return;

                timeOut = setTimeout(() => {
                    updateForm(avatar, userName)
                        .finally(() => {
                            clearTimeout(timeOut);
                            timeOut = undefined;
                        });
                }, 750);
            });
        }
    };

    const initQuickSubmit = () => {
        const elems = Array.from($qa('.js-quick-submit, .js-ctrl-enter-submit'));
        if(elems.length < 1)
            return;

        for(const elem of elems)
            elem.addEventListener('keydown', ev => {
                if((ev.code === 'Enter' || ev.code === 'NumpadEnter') && ev.ctrlKey && !ev.altKey && !ev.shiftKey && !ev.metaKey) {
                    // hack: prevent forum editor from screaming when using this keycombo
                    //       can probably be done in a less stupid manner
                    MszForumEditorAllowClose = true;

                    elem.form.submit();
                    ev.preventDefault();
                }
            });
    };

    try {
        MszSakuya.trackElements($qa('time'));
        hljs.highlightAll();

        MszEmbed.init(`${location.protocol}//uiharu.${location.host}`);

        // only used by the forum posting form
        initQuickSubmit();
        const forumPostingForm = $q('.js-forum-posting');
        if(forumPostingForm !== null)
            MszForumEditor(forumPostingForm);

        const events = new MszSeasonalEvents;
        events.add(new MszChristmas2019EventInfo);
        events.dispatch();

        await initLoginPage();

        MszMessages();

        MszEmbed.handle($qa('.js-msz-embed-media'));
    } catch(ex) {
        console.error(ex);
    }
})();
