import { Sprite, Texture, interaction } from "pixi.js"
import globals from "../globals"
import { TooltipSystem } from "../Systems/UI/TooltipSystem"
import { hide, show } from "../util"

export class Button extends Sprite {
  //TODO: sound utility

  defaultSprite: Texture
  hoverSprite: Texture
  clickSprite: Texture

  hovered = false
  clicked = false

  tooltipText = ""

  setTooltip(tooltip: string) {
    this.tooltipText = tooltip
  }

  constructor(texture?: Texture) {
    super()

    this.defaultSprite = texture

    this.texture = texture
    this.interactive = true

    this.on("pointerover", this.startHover)
    this.on("pointerout", this.endHover)
    this.on("pointercancel", this.endHover)
    this.on(hide, this.endHover)
    this.on(show, this.tryCatchMouse)

    this.on("pointerdown", this.startClick)
    this.on("pointerup", this.endClick)
    this.on("pointerupoutside", this.endClick)
  }

  startHover() {
    this.hovered = true
    this.updateSprite()
    this.showTooltip()
  }

  endHover() {
    this.hovered = false
    this.updateSprite()
    this.hideTooltip()
  }

  startClick() {
    this.clicked = true
    this.updateSprite()
  }

  endClick() {
    this.clicked = false
    this.updateSprite()
  }

  showTooltip() {
    let ttSystem = globals.world.getSystem(TooltipSystem) as TooltipSystem
    ttSystem?.showTooltip(this.tooltipText, this)
  }

  hideTooltip() {
    let ttSystem = globals.world.getSystem(TooltipSystem) as TooltipSystem
    ttSystem?.cancelTooltip(this)
  }

  updateSprite() {
    if (this.clicked && this.clickSprite) {
      this.texture = this.clickSprite
      return
    }
    if (this.hovered && this.hoverSprite) {
      this.texture = this.hoverSprite
      return
    }
    this.texture = this.defaultSprite
  }

  tryCatchMouse() {
    let mousePos = globals.app.renderer.plugins.interaction.mouse.global
    if (this.getBounds().contains(mousePos.x, mousePos.y)) {
      this.startHover()
    }
  }

  onClick(action: (event: interaction.InteractionEvent) => void, context: any) {
    this.on("click", action, context)
  }
}
