import { Container, Text, Sprite, Loader, Texture, interaction } from "pixi.js"

import { Point } from "../Datatypes/MathTypes/point"
import { InfoSystem } from "../Systems/UI/InfoSystem"
import { Name } from "../Components/name"
import { Entity } from "ecsy"
import { Button } from "./Button"

export class InfoMenu extends Container {
  system: InfoSystem

  nameField: Text
  portrait: Sprite

  constructor(system: InfoSystem) {
    super()

    this.system = system

    this.setupName()
    this.setupPortrait()
    this.setupButtons()

    this.visible = false
  }

  setupName() {
    let name = new Text("-", {
      fontFamily: "babyblocks",
      fontSize: 16,
      fill: 0xffffff,
    })
    name.position = new Point(64 + 2, 1)
    this.addChild(name)
    this.nameField = name
  }

  setupPortrait() {
    let portait = new Sprite(null)
    portait.position = new Point(0, 0)
    this.addChild(portait)
    this.portrait = portait
  }

  setupButtons() {
    let buttons = Loader.shared.resources["AdventureButtons"].textures
    let buttonDef: {
      texture: Texture
      tooltip?: string
      action?: (event: interaction.InteractionEvent) => void
      context?: any
    }[] = [
      {
        texture: buttons["New"],
        tooltip: "New Adventure",
        action: this.system.createAdventure,
        context: this.system,
      },
    ]

    let container = new Container()
    this.addChild(container)
    container.position = new Point(0, 126 - 18)

    for (let i = 0; i < buttonDef.length; i++) {
      let def = buttonDef[i]
      let button = new Button(def.texture)

      if (def.action) button.onClick(def.action, def.context)
      if (def.tooltip) button.setTooltip(def.tooltip)

      container.addChild(button)
      button.position = new Point(i * 18, 0)
    }
  }

  select(entity: Entity) {
    let name = entity?.getComponent(Name)?.fullName() || "-"
    this.nameField.text = name

    let face = entity ? Loader.shared.resources["Face"].texture : null
    this.portrait.texture = face
  }
}
