#include csrfp.js
#include utility.js

const MszMessagesRecipient = function(element) {
    if(!(element instanceof Element))
        throw 'element must be an instance of Element';

    const avatarElem = element.querySelector('.js-messages-recipient-avatar img');
    const nameInput = element.querySelector('.js-messages-recipient-name');

    let updateHandler = undefined;
    const update = async () => {
        const result = await $x.post(element.dataset.msgLookup, { type: 'json' }, {
            _csrfp: MszCSRFP.getToken(),
            name: nameInput.value,
        });

        MszCSRFP.setFromHeaders(result);

        const body = result.body();

        if(updateHandler !== undefined)
            await updateHandler(body);

        if(typeof body.avatar === 'string')
            avatarElem.src = body.avatar;

        if(typeof body.name === 'string')
            nameInput.value = body.name;
    };

    let nameTimeout = null;
    nameInput.addEventListener('input', () => {
        if(nameTimeout !== undefined)
            return;

        nameTimeout = setTimeout(() => {
            update().finally(() => {
                clearTimeout(nameTimeout);
                nameTimeout = undefined;
            });
        }, 750);
    });

    update().finally(() => nameTimeout = undefined);

    return {
        getElement: () => element,
        onUpdate: handler => {
            if(typeof handler !== 'function')
                throw 'handler must be a function';

            updateHandler = handler;
        },
    };
};
