const app = window.app ??= {}
const view = window.view ??= {}

import Store from 'store'
import * as device from 'device'
import * as browser from './browser.js'
import * as entry from './entry.js'
import * as mode from './mode.js'

export let store
export let saveTimeout

export const Start = async () => {
    store = await Store.Open('app', 'data')
    await device.Start()
    await entry.Start()
    let success = await loadState()

    if(!success) {
        await Init()
    }

    window.addEventListener('visibilitychange', async event => {
        if(document.visibilityState !== 'visible') {
            await saveState()
        }
    })

    await View()
    view.loading.remove()
}

export const Init = async () => {
    mode.Init()
    await entry.Init()
    await browser.Init()
    await queue.Init()
    await player.Init()
}

export const View = async () => {
    view.main = document.getElementById('main')
    view.loading = document.getElementById('loading')
    view.loadingStatus = document.getElementById('loading-status')

    await browser.View()
    await queue.View()
    await player.View()
    mode.View()
    
    window.addEventListener('keydown', OnKeydown)

    // player.Render({ name: 'Timeland, Smoke & Mirrors, The Land Before Timeland, & Hypertension', artist: 'King Gizzard & The Lizard Wizard' })
}

export const loadState = async () => {
    let state = await store.Get('state')
    Object.assign(app, state)

    return state != undefined
}

export const saveState = () => {
    app.lastSaved = Date.now()
    console.log('saving')
    return store.Set('state', app)
}

export const resetSaveTimer = () => {
    if(saveTimeout)
        clearTimeout(saveTimeout)
    saveTimeout = setTimeout(() => saveState(), 10 * 1000) 
}

export const Reload = async () => {
    await store.Set('state', null)
    window.location.reload()
}

export const OnKeydown = (event) => {
    switch(event.key) {
        case 'EndCall':
            saveState().then(() => window.close())
            break

        case '1':
            mode.Set(mode.states.PLAYER)
            break

        case '2':
            mode.Set(mode.states.BROWSER)
            break

        case '3':
            mode.Set(mode.states.QUEUE)
            break

        case '0':
            main.Reload()
            break

        case 'ArrowLeft':
            mode.Scroll(-1)
            break

        case 'ArrowRight':
            mode.Scroll(1)
            break

        default:
            if(mode.OnKeydown(event))
                return
    }

    event.preventDefault()
    resetSaveTimer()
}