import Phaser from "phaser";

const WHITE = 0xffffff;
const OFFWHITE = 0xeeeeee;

export default class Button extends Phaser.GameObjects.Graphics {
  constructor(
    scene,
    x,
    y,
    width,
    height,
    radius = 16,
    label = "",
    labelSize = 20,
    color = OFFWHITE
  ) {
    super(scene);

    this.fillStyle(color);
    this.fillRoundedRect(x, y, width, height, radius); // avoid redraw later

    this.hitRect = scene.add.rectangle(x, y, width, height);
    this.setInteractive(this.hitRect, Phaser.Geom.Rectangle.Contains)
      .on("pointerup", this.handleUp, this)
      .on("pointerout", this.handleOut, this)
      .on("pointerdown", this.handleDown, this)
      .on("pointerover", this.handleOver, this);

    this.pressedRect = scene.add.rectangle(
      x + width * (1 / 2),
      y + height * (1 / 2),
      width * (4 / 5),
      height * (4 / 5),
      0x000000,
      1
    ); // add a rectangle to show when the button is pressed
    this.pressedRect.setAlpha(0); // needed for it to show at all
    this.pressedRect.setDepth(1); // bring to front

    this.label = scene.add
      .text(x, y, label, {
        fontFamily: "sans-serif",
        fontSize: labelSize,
        color: "#000000",
        align: "center",
        wordWrap: { width: width + 4, useAdvancedWrap: true }
      })
      .setDepth(1);
    this.setLabel(label);
  }

  handleUp(pointer) {
    this.handleOut(pointer);
  }

  handleOut(pointer) {
    this.pressedRect.setAlpha(0);
  }

  handleDown(pointer) {
    this.pressedRect.setAlpha(0.25);
  }

  handleOver(pointer) {
    if (pointer.wasTouch) this.pressedRect.setAlpha(0.25);
  }

  setLabel(label) {
    this.label.setText(label);
    this.label.setX(this.hitRect.x + (this.hitRect.width - this.label.width) / 2); // (bWidth - tWidth) / 2 = margin
    this.label.setY(this.hitRect.y + (this.hitRect.height - this.label.height) / 2); // (bHeight - tHeight) / 2 = margin
  }
}
