import substr from './string/substr.js';
import extend from './object/extend.js';
import addColors from './style/addColors.js';
import link from './ajax/link.js';
import resize from './style/resize.js';
import isMobile from './browser/isMobile.js';
import isTabletDevice from './browser/isTabletDevice.js';
import isFunction from './type/isFunction.js';
import log from './browser/log.js';
import timestamp from './datetime/timestamp.js';
import setupIntl from '../dt/functions/setupIntl.js';
const onFocus = () => {
    bbn.env.last_focus = bbn.dt().unix();
};
const onActivity = (e) => {
    onFocus();
    if (bbn.env.nav !== "ajax") {
        return;
    }
    let target = e.target;
    if (target instanceof HTMLElement && target.tagName !== "A") {
        let p = target;
        while (p && p.tagName !== "A") {
            if (p.tagName === "BODY") {
                break;
            }
            p = p.parentElement;
        }
        if (p && p.tagName === "A") {
            target = p;
        }
        else {
            target = null;
        }
    }
    if (target instanceof HTMLElement &&
        target.hasAttribute("href") &&
        !target.hasAttribute("target") &&
        !target.classList.contains("bbn-no")) {
        log("Link clicked: " + target.getAttribute("href"));
        link(target.getAttribute("href"), e);
    }
};
/**
 * Initializes the library bbn basing on the given configuration object.
 * - Gives to the environment the dimension of the window.innerWidth and window.innerHeight
 * - Defines the server's path (difference between the host and the current dir)
 * - Adds the colors contained in bbn.data.colors to define the css classes for background and colors.
 * - Adds the event listener to the document
 * - Activates the history
 * @method   init
 * @global
 * @memberof bbn.fn
 * @param    {Object} cfg
 * @returns
 */
export default function init(cfg, force) {
    if (!bbn.env.isInit) {
        bbn.env.root = globalThis.document?.baseURI?.length ? globalThis.document.baseURI : bbn.env.host;
        if (bbn.env.root.length && substr(bbn.env.root, -1) !== "/") {
            bbn.env.root += "/";
        }
        /* The server's path (difference between the host and the current dir */
        if (typeof cfg === "object") {
            extend(true, bbn, cfg);
        }
        const [path, getParams] = bbn.env.url.split('?');
        const getParameters = getParams ? getParams.split('&').reduce((acc, param) => {
            const [key, value] = param.split('=');
            acc[key] = value;
            return acc;
        }, {}) : {};
        bbn.env.getParameters = getParameters;
        bbn.env.path = substr(path, bbn.env.root.length);
        // Params will include each part of the URL
        bbn.env.params = bbn.env.path.split('/').filter(v => v !== '');
        setupIntl();
        if (globalThis.document) {
            if (bbn.data.colors) {
                addColors(bbn.data.colors);
            }
            document.addEventListener("visibilitychange", () => {
                if (document.hidden) {
                    bbn.env.isVisible = false;
                }
                else {
                    bbn.env.isVisible = true;
                }
            });
            document.addEventListener("focus", (e) => {
                if (e.target instanceof HTMLElement &&
                    !e.target.classList.contains("bbn-no")) {
                    bbn.env.focused = e.target;
                }
                bbn.env.isFocused = true;
                bbn.env.last_focus = timestamp();
            });
            document.addEventListener("blur", (e) => {
                if (e.target instanceof HTMLElement &&
                    !e.target.classList.contains("bbn-no")) {
                    bbn.env.focused = e.target;
                }
                bbn.env.isFocused = false;
                bbn.env.last_focus = timestamp();
            });
            document.addEventListener("click", onActivity);
            document.addEventListener("keydown", onActivity);
            document.addEventListener("focusin", onFocus);
            document.addEventListener("focusout", onFocus);
            window.addEventListener("hashchange", () => {
                bbn.env.hashChanged = new Date().getTime();
            }, false);
            window.addEventListener("resize", () => {
                resize();
            });
            window.addEventListener("orientationchange", () => {
                resize();
            });
            resize();
            if (isMobile()) {
                document.body.classList.add("bbn-mobile");
                if (isTabletDevice()) {
                    document.body.classList.add("bbn-tablet");
                }
            }
            if (window.history) {
                window.onpopstate = function (e) {
                    let h = window.history;
                    if (!bbn.env.historyDisabled && h) {
                        //e.preventDefault();
                        if (bbn.fn.defaultHistoryFunction(h.state)) {
                            let state = h.state;
                            if (state) {
                                //link(substr(state.url, bbn.env.root.length), $.extend({title: state.title}, state.data));
                                link(state.url, extend({ title: state.title || bbn.env.siteTitle }, state.data || {}));
                            }
                            else if (state && state.data && isFunction(state.data.script)) {
                                state.data.script();
                            }
                        }
                    }
                };
            }
            window.addEventListener('online', () => {
                bbn.env.online = true;
            });
            window.addEventListener('offline', () => {
                bbn.env.online = false;
            });
            bbn.env.isInit = true;
            document.dispatchEvent(new Event("bbninit"));
        }
    }
}
;
