/**
 * To hold third party global instance
 * Ex: To create and initialize global instance of Insights framework
 */
(function(w) {
    window.AppGlobals = {};

    /**
     * Initialize Insights
     * @type {*}
     */
    const insightsTransactionId = getUniqueFlowId();

    /**
     * Get unique flow id
     * @returns {string}
     */
    function getUniqueFlowId() {
        let flowId =
            (Math.random() + 1).toString(36).substring(3) +
            "-" +
            new Date().toISOString();
        return flowId.toLowerCase();
    }

    window.AppGlobals = Object.freeze({
        IF_TRANSACTION_ID: insightsTransactionId,
        IF_EVENTS: initInsights(insightsTransactionId),
    });

    //Check if object is empty
    function isEmptyObject(value) {
        return (
            Object.prototype.toString.call(value) === "[object Object]" &&
            JSON.stringify(value) === "{}"
        );
    }

    /**
     * Take query string from url, check if query string present and returns array of params list,
     * If query string is undefined returns empty string.
     * @returns {*} returns array of params
     */
    function getParametersKeyFromUrl() {
        let urlParams = window.location.search;

        if (urlParams.split("?")[1]) {
            return urlParams.split("?")[1].split("&");
        }
        return "";
    }

    function initInsights(insightsTransactionId) {
        if (typeof Insights != "undefined") {
            /* eslint-disable no-undef */
            Object.defineProperty(Insights, "transactionId", {
                value: insightsTransactionId,
                writable: false,
            });

            let events = Insights.init(window.location.hostname);
            console.log(`App: Insights enabled for ${window.location.hostname}`);
            return events;
        } else {
            console.log("App: Insights object not available");
        }
    }

    /**
     * Send insights wrapper functions
     * @param verbName
     * @param objectDefinationName
     * @param contextObj
     */
    function sendInsightsEvents(userId, verbName, objectDefinationName, contextObj) {
        const PAGE_URL_PATH = window.location.href.split(window.location.host)[1];
        const events = window.AppGlobals.IF_EVENTS;
	  
        if (!isEmptyObject(events)) {
            let pageUrl = PAGE_URL_PATH;
            const SYSTEM_DATA = getSystemDetails();
            if(sessionStorage.getItem("last_page_url") == null) {
                sessionStorage.setItem("last_page_url", window.location.href);
            }
            const prevUrl = sessionStorage.getItem("last_page_url");
            let defaultContext = {
                app:"experience cloud",
                transactionId: window.Insights.transactionId,
                url: PAGE_URL_PATH,
                referrer: prevUrl, //document.referrer,
                title: document.title,
                params: getParametersKeyFromUrl().toString(),
                browserName: SYSTEM_DATA.browser,
                oSName: SYSTEM_DATA.oSName,
                deviceType: getDeviceType()
            };

            // Merge default article context and passed contexts
            let context = Object.assign({}, defaultContext, contextObj);

            AppGlobals.IF_EVENTS.send(
                userId,
                verbName,
                pageUrl,
                objectDefinationName,
                context
            );
        }
    }

    // Send error insights event in case of error
    // Verb name: error
    // Object definition name: error
    function sendErrorInsightsEvent(errorMessage, errorObject) {
        sendInsightsEvents("error", "error", {
            errorMessage: errorMessage,
            errorObject: errorObject,
        });
    }

    //get device type 
    function getDeviceType() {
        return window.innerWidth < 767 ? "Mobile": "Desktop";
    }
    
    // get system details ex: OS name , browser name
    function getSystemDetails() {
        var data = {oSName:'',browser:''};
        //get OS Info
        if (window.navigator.userAgent.indexOf("Windows NT 10.0")!= -1) data.oSName="Windows 10";
        if (window.navigator.userAgent.indexOf("Windows NT 6.3") != -1) data.oSName="Windows 8.1";
        if (window.navigator.userAgent.indexOf("Windows NT 6.2") != -1) data.oSName="Windows 8";
        if (window.navigator.userAgent.indexOf("Windows NT 6.1") != -1) data.oSName="Windows 7";
        if (window.navigator.userAgent.indexOf("Windows NT 6.0") != -1) data.oSName="Windows Vista";
        if (window.navigator.userAgent.indexOf("Windows NT 5.1") != -1) data.oSName="Windows XP";
        if (window.navigator.userAgent.indexOf("Windows NT 5.0") != -1) data.oSName="Windows 2000";
        if (window.navigator.userAgent.indexOf("Mac") != -1) data.oSName="Mac OS";
        if (window.navigator.userAgent.indexOf("X11") != -1) data.oSName="UNIX";
        if (window.navigator.userAgent.indexOf("Linux") != -1) data.oSName="Linux";
    
        // get Browser Info
        if ((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1) {
            data.browser = 'Opera';
        } else if (navigator.userAgent.indexOf("Edg") != -1) {
            data.browser = 'Edge';
        } else if (navigator.userAgent.indexOf("Chrome") != -1) {
            data.browser = 'Chrome';
        } else if (navigator.userAgent.indexOf("Safari") != -1) {
            data.browser = 'Safari';
        } else if (navigator.userAgent.indexOf("Firefox") != -1) {
            data.browser = 'Firefox';
        } else if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)){
            data.browser = 'IE';
        } else {
            data.browser = 'unknown';
        }
        return data;
    }
    w.sendInsightsEvents = sendInsightsEvents;
    w.sendErrorInsightsEvent = sendErrorInsightsEvent;

})(window);
