import List from "./list.js"

import * as mode from "./mode.js"
import * as player from "./player.js"
import { OnEntryListKeydown } from "./util.js"

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

export let list

export const Init = async () => {
    app.queue = []
}

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

export const Render = async () => {
    list.Render(app.queue)
}

export const OnKeydown = (event) => {
    let e = Focused()

    switch(event.key) {
        // case 'ArrowLeft':
        //     back()
        //     break

        // case 'ArrowRight':
        //     cd(e)
        //     break

        case '[':
        case 'SoftLeft':
            // Move track up
            Move(e, -1)
            break

        case ']':
        case 'SoftRight':
            // Move track down
            Move(e, 1)
            break;

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

export const Move = (eTrack, offset) => {
    let i = view.queue.cursor + offset
    if(i == app.queue.length || i < 0) {
        return
    }
    let n = app.queue[i]
    app.queue[view.queue.cursor] = n
    app.queue[i] = eTrack
    list.Render(app.queue, i)
}

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


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

export const Add = (eTrack) => {
    // TODO: solid way to determine if something is playable
    app.queue.push(eTrack)
    if(app.queue.length == 1 && player.State() === player.states.EMPTY) {
        player.Next()
    }
}

export const Shift = () => {
    let e

    if(app.queue.length > 0) {
        e = app.queue.shift()
        Render()
        return e
    }

}