import { Container, DisplayObject } from "pixi.js"
import { AABB } from "../../Datatypes/MathTypes/aabb"
import { System, Entity } from "ecsy"
import globals from "../../globals"
import { Adventure } from "../../Components/adventure"
import { InfoMenu } from "../../UI/InfoMenu"
import { PlanningMenu } from "../../UI/PlanningMenu"
import { setVisible } from "../../util"

enum InfoState {
  None,
  Planning,
  Arriving,
  Info,
}

// InfoSystem
export class InfoSystem extends System {
  priority = 60

  root: Container
  elements: { [id: string]: DisplayObject } = {}

  state = InfoState.Info
  creatingAdventure: Entity

  infoMenu: InfoMenu
  planningMenu: PlanningMenu
  arrivalMenu: Container

  init() {
    let bounds = new AABB(0, 162, 162, 126)

    this.root = globals.app.stage.addChild(new Container())
    this.root.position = bounds.min()
    this.root.zIndex = 1000

    this.infoMenu = new InfoMenu(this)
    this.planningMenu = new PlanningMenu(this)
    this.root.addChild(this.infoMenu, this.planningMenu)

    globals.selected.onChange((selected) => this.select(selected))

    this.infoMenu.visible = true
  }

  setState(newState: InfoState) {
    let previousStateMenu = this.getStateMenu(this.state)
    let nextStateMenu = this.getStateMenu(newState)
    if (previousStateMenu) setVisible(previousStateMenu, false)
    if (nextStateMenu) setVisible(nextStateMenu, true)
    this.state = newState
  }

  getStateMenu(state: InfoState): Container {
    switch (state) {
      case InfoState.Info:
        return this.infoMenu
      case InfoState.Planning:
        return this.planningMenu
      case InfoState.Arriving:
        return this.arrivalMenu
    }
    return null
  }

  createAdventure() {
    let adventureEntity = globals.world.createEntity().addComponent(Adventure)
    this.creatingAdventure = adventureEntity
    this.setState(InfoState.Planning)
  }

  abortPlans() {
    this.creatingAdventure.remove()
    this.setState(InfoState.Info)
  }

  select(entity: Entity) {
    if (this.state === InfoState.Info) {
      this.infoMenu.select(entity)
    }
    if (this.state === InfoState.Planning) {
    }
  }

  execute(delta: number) {}

  static queries = {}
  queries: any
}
