import { ContextI } from '../ContextI'
import { StateI } from './StateI'
import * as PIXI from 'pixi.js'
import { GameState } from './Game'

interface MenuItem {
  text: PIXI.Text,
}

export function MenuState(ctx: ContextI): StateI {
  let container = new PIXI.Container()

  let text = new PIXI.Text('GGJ22', new PIXI.TextStyle({
    fontFamily: 'Arial',
    fontSize: 40,
    dropShadow: true,
    fill: ['#ffffff'],
    stroke: '#000000',
  }))

  let hoverStyle = new PIXI.TextStyle({
    fontFamily: 'Arial',
    fontSize: 20,
    dropShadow: true,
    stroke: '#ffffff',
    fill: '#9999dd',
  })
  let blurStyle = new PIXI.TextStyle({
    fontFamily: 'Arial',
    fontSize: 20,
    dropShadow: true,
    fill: ['#ffffff'],
    stroke: '#000000',
  })

  let menuItems: PIXI.Text[] = []

  {
    let el = new PIXI.Text('Start Game', blurStyle)
    el.interactive = true
    el.on('pointerdown', () => {
      ctx.push(GameState(ctx))
    })
    el.on('pointerover', () => {
      el.style = hoverStyle
    })
    el.on('pointerout', () => {
      el.style = blurStyle
    })
    menuItems.push(el)
    container.addChild(el)
  }

  container.addChild(text)

  let enter = () => {
    console.log('MenuState.enter')
    ctx.app.stage.addChild(container)
  }
  let leave = () => {
    console.log('MenuState.leave')
    ctx.app.stage.removeChild(container)
  }
  let update = (delta: number) => {
    let yPos = 32
    // Eh... this isn't too expensive.
    text.x = ctx.app.view.width / 2 - text.width / 2
    text.y = 32
    yPos += text.height + 32
    for (let item of menuItems) {
      item.x = ctx.app.view.width / 2 - item.width / 2
      item.y = yPos
      yPos += item.height + 8
    }
  }

  return {
    enter,
    leave,
    update,
  }
}
