import './style.css'

import * as welcome from "./welcome"
import * as jugando from "./jugando"

function update(juego: Juego<any>, dt: number) {
    switch (juego.state.current) {
        case "welcome":
            welcome.update(juego, dt)
            break
        case "jugando":
            jugando.update(juego, dt)
            break
    }
}

function draw(juego: Juego<any>, timestamp: number) {
    const { width, height } = juego.canvas

    juego.ctx.clearRect(0, 0, width, height)
    switch (juego.state.current) {
        case "welcome":
            welcome.draw(juego, timestamp)
            break
        case "jugando":
            jugando.draw(juego, timestamp)
            break
    }
}

function resizeCanvas(canvas: HTMLCanvasElement) {
    canvas.width = canvas.clientWidth
    canvas.height = canvas.clientHeight
}

export type State = welcome.State | jugando.State

export type Juego<T extends State> = {
    canvas: HTMLCanvasElement
    ctx: CanvasRenderingContext2D
    mouse: { x: number; y: number, down: boolean }
    keyboard: { keys: { [key: string]: boolean } }
    state: T
}

function initJuego() {
    const canvas = document.querySelector<HTMLCanvasElement>("#juego")!
    const ctx = canvas.getContext("2d")!

    window.addEventListener("resize", () => resizeCanvas(canvas), false)
    resizeCanvas(canvas)

    let juego: Juego<welcome.State> = {
        canvas,
        ctx,
        mouse: { x: 0, y: 0, down: false },
        keyboard: { keys: {} },
        state: {
            current: "welcome",
        },
    };
    (window as any).juego = juego

    canvas.addEventListener("mousemove", e => {
        juego.mouse.x = e.clientX
        juego.mouse.y = e.clientY
    }, false)
    canvas.addEventListener("mousedown", () => {
        juego.mouse.down = true
    }, false)
    canvas.addEventListener("mouseup", () => {
        juego.mouse.down = false
    }, false)
    window.addEventListener("keydown", e => {
        juego.keyboard.keys[e.key] = true
    })
    window.addEventListener("keyup", e => {
        juego.keyboard.keys[e.key] = false
    })

    let lastRender = 0
    const loop: FrameRequestCallback = timestamp => {
        const progress = timestamp - lastRender

        update(juego, progress)
        draw(juego, timestamp)

        lastRender = timestamp
        window.requestAnimationFrame(loop)
    }

    window.requestAnimationFrame(loop)
}
initJuego()
