// entry - a track, directory, playlist, etc
// - entries
// - name
// - length

import List from "./list.js"
import * as entry from "./entry.js"
import * as mode from "./mode.js"
import * as device from "device"
import { OnEntryListKeydown } from "./util.js"

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

export let list

export const Init = async () => {
    app.browser = {}
    app.browser.root = {
        entries: app.index,
        root: true
    }
    app.browser.current = app.browser.root
    app.browser.recursiveView = false
    app.browser.view = []
}

export const View = async () => {
    list = new List(
        view.browser = {},
        document.getElementById('browser')
    )
    Render()
}

export const Render = async () => {
    organizeView()
    list.Render(app.browser.view, 0)
}

export const organizeView = () => {
    if(app.browser.recursiveView) {
        app.browser.view = []
        recurseView()
    } else {
        app.browser.view = app.browser.current.entries
    }
    app.browser.view.sort((a, b) => a.order - b.order)
}

export const recurseView = (eaEntries = app.browser.current.entries, bIncludeDirectories = true) => {
    for(let e of eaEntries) {
        if(e.entries) {
            recurseView(e.entries, false)
            if(!bIncludeDirectories)
                continue
        }
        app.browser.view.push(e)
    }
}

export const Open = () => {
    mode.Display('browser')
}

export const OnKeydown = (event) => {
    let e = Focused()
    
    switch(event.key) {
        case 'SoftLeft':
            // PlayTrack()
            break

        case 'Escape':
        case 'Backspace':
            back()
            break

        case ' ':
        case 'Enter':
            if(e.entries) {
                Cd(e)
                break
            }
        case 'q':
            if(e.entries == null) {
                queue.Add(e)
            }
            list.Scroll(1)
            break;

        case 'r':
        case '7':
            app.browser.recursiveView = !app.browser.recursiveView
            Render() 
            break

        default:
            return OnEntryListKeydown(list, event, e)
    }
}

export const back = () => {
    let e = app.browser.current
    if(e.root) {
        return
    }
    let s = Cd(e.parent)
    
    if(s) {
        list.Focus(app.browser.view.indexOf(e))
    }
}

export const Cd = (entry = app.browser.root) => {
    if(entry.entries) {
        app.browser.current = entry
        Render()

        return true
    } else {
        return false
    }
}


export const Focused = () => {
    return app.browser.view[view.browser.cursor]
}