import * as PIXI from 'pixi.js'
import { ContextI } from './ContextI'
import { MenuState } from './states/Menu'
import { StateI } from './states/StateI'
import { decors } from './shared/decors'
import { segments } from './shared/segments'
import { sprites } from './shared/sprites'

export class Engine {
  ctx: ContextI
  element: HTMLElement
  background: PIXI.Container
  midground: PIXI.Container
  foreground: PIXI.Container
  states: StateI[]

  constructor(target: HTMLElement) {
    this.element = target

    console.log(
      decors,
      segments,
      sprites,
    )

    // Setup
    this.states = []
    this.ctx = {
      app: new PIXI.Application({
        backgroundColor: 0x222222,
        resizeTo: target,
      }),
      push: (state: StateI) => this.pushState(state),
      pop: () => this.popState(),
    }

    this.ctx.app.ticker.add((d) => {
      this.update(d)
    })

    this.ctx.app.stage.addChild(this.background = new PIXI.Container())
    this.ctx.app.stage.addChild(this.midground = new PIXI.Container())
    this.ctx.app.stage.addChild(this.foreground = new PIXI.Container())

    window.addEventListener('resize', () => {
      this.refresh()
    })
    this.refresh()

    target.appendChild(this.ctx.app.view)

    // Add our state!
    this.pushState(MenuState(this.ctx))
  }

  refresh() {
    this.ctx.app.resize()
  }

  update(delta: number) {
    let top = this.states[this.states.length-1]
    if (top) {
      top.update(delta)
    }
  }

  pushState(state: StateI) {
    let top = this.states[this.states.length-1]
    if (top) {
      top.leave()
    }
    this.states.push(state)
    state.enter()
  }
  popState() {
    let state = this.states.pop()
    if (state) {
      state.leave()
    }
    let top = this.states[this.states.length-1]
    if (top) {
      top.enter()
    }
  }
}