import isBrowser from "is-in-browser";

import {
    listenApplicationClose,
    listenApplicationVisibilityChange,
    listenPageChanged,
    listenPageScrolled
} from "../drivers/CfSystem";
import CfLog from "../modules/CfLog";
import Navigation from "../modules/Navigation";
import {AppAction, AppProperties, NavigationTypes, PageProperties} from "../modules/Navigation/typings";

let lastPageChangeTimestamp = null

let currentPageURL = ''
let currentTitle = ''
let spaRenderTime = 0

const logOpenAppEvent = () => {
    lastPageChangeTimestamp = new Date()
    currentPageURL = window.location.href
    currentTitle = document.title

    const perfEntries = performance.getEntriesByType("navigation");

    let startTime = Math.round((typeof perfEntries[0] === 'undefined') ? 0 : perfEntries[0].duration)
    if(startTime > 30000){ // should not be greater than 30 sec which is the default timeout.
        startTime = 0
    }

    const appProperties: AppProperties = {
        action: AppAction.Open,
        start_time: startTime
    }

    Navigation.logIngestEvent(NavigationTypes.App, appProperties)
}

const logBackgroundEvent = () => {
    logPageChangedEvent(currentPageURL, currentTitle)
    const appProperties: AppProperties = {
        action: AppAction.Background,
        start_time : 0
    }

    Navigation.logIngestEvent(NavigationTypes.App, appProperties)
}


const logResumeEvent = () => {
    lastPageChangeTimestamp = new Date()
    const appProperties: AppProperties = {
        action: AppAction.Resume,
        start_time : 0
    }

    Navigation.logIngestEvent(NavigationTypes.App, appProperties)
}

const logPageChangedEvent = (path, title) => {
    const currentTimestamp = Date.now()
    const duration = Math.round((currentTimestamp - lastPageChangeTimestamp) / 1000)
    let render_time = 0
    const perfEntries = performance.getEntriesByType("navigation");
    const pageDuration = Math.round((typeof perfEntries[0] === 'undefined') ? 0 : perfEntries[0].duration)
    if(spaRenderTime != pageDuration){
        render_time = spaRenderTime = pageDuration
        if(render_time > 30000){
            render_time = 0
        }
    }else{
        render_time = 0
    }

    const properties: PageProperties = {
        path,
        title,
        duration,
        render_time
    }

    lastPageChangeTimestamp = currentTimestamp
    Navigation.logIngestEvent(NavigationTypes.Page, properties)
}

const logPageCompletedEvent = (path, title) => {
    const render_time = 0
    const properties: PageProperties = {
        path,
        title,
        render_time
    }

    Navigation.logIngestEvent(NavigationTypes.Page, properties)
}


export const init = (cfLog: CfLog) => {

    if (!isBrowser) {
        return
    }
    let lastCompletedPageTracked = ''

    // This function is called just once, so
    // it is a good point to log the open event
    // Previous implementation relied this on
    // navigator listeners, but I did not find
    // a homogenous behaviour across browsers
    logOpenAppEvent()

    listenApplicationClose(() => {
        // console.warn('application is about to close: ', document.visibilityState)
        // cfLog.flush()
    })

    listenApplicationVisibilityChange(logResumeEvent, logBackgroundEvent)

    listenPageChanged((path, title) => {
        lastCompletedPageTracked=''

        logPageChangedEvent(currentPageURL, currentTitle)

        currentPageURL = path
        currentTitle = title
    })
}

export default init
