#include utility.js

const MszCSRFP = (() => {
    let elem;
    const getElement = () => {
        if(elem === undefined)
            elem = $q('meta[name="csrfp-token"]');
        return elem;
    };

    const getToken = () => {
        const elem = getElement();
        return typeof elem.content === 'string' ? elem.content : '';
    };

    const setToken = token => {
        if(typeof token !== 'string')
            throw 'token must be a string';

        const elem = getElement();
        if(typeof elem.content === 'string')
            elem.content = token;
    };

    return {
        getToken: getToken,
        setToken: setToken,
        setFromHeaders: result => {
            if(typeof result.headers !== 'function')
                throw 'result.headers is not a function';

            const headers = result.headers();
            if(!(headers instanceof Map))
                throw 'result of result.headers does not return a map';

            if(headers.has('x-csrfp-token'))
                setToken(headers.get('x-csrfp-token'));
        },
    };
})();
