window.onload = function () {

    const ui = window.ui;

    // intercept response
    const originalFetch = window.fetch;

    window.fetch = async (...args) => {

        const response = await originalFetch(...args);

        try {

            const url = args[0];

            // login endpoint
            if (url.includes('/api/Token')) {

                const cloned = response.clone();
                const data = await cloned.json();

                if (data.isOk) {

                    localStorage.setItem(
                        "api_token",
                        data.object
                    );
                }
            }

        } catch (e) {
            console.log(e);
        }

        return response;
    };

    // inject token into requests
    ui.getConfigs().requestInterceptor = (req) => {

        const token = localStorage.getItem("api_token");

        if (token) {

            try {

                if (req.body) {

                    let body = JSON.parse(req.body);

                    body.token = token;

                    req.body = JSON.stringify(body);
                }

            } catch (e) {
                console.log(e);
            }
        }

        return req;
    };
};