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
  states: StateI[]

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

    console.log(
      decors,
      segments,
      sprites,
    )

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

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

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

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

  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()
    }
  }
}