package game.ui;

import base.GameSprite;

import openfl.text.TextField;
import openfl.text.TextFormat;
import openfl.text.TextFieldAutoSize;
import openfl.events.MouseEvent;
import openfl.Assets;
import openfl.display.Bitmap;

class SpeechSentence extends GameSprite {
  static var textFormat: TextFormat = null;

  var textField : TextField;
  var time: Float;
  var callback: Void -> Void;
  var onFinish: Void -> Void;
  var btnSkip: Bitmap;

  public function new(text: String, time: Null<Float> = null, onFinish: Void -> Void, callback: Void -> Void) {
    super();

    if(textFormat == null) {
      textFormat = new TextFormat(Assets.getFont('font/basis33.ttf').fontName, 10, 0xaeaeae);
    }

    textField = new TextField();
    textField.selectable = false;
    textField.setTextFormat(textFormat);
    textField.autoSize = TextFieldAutoSize.LEFT;
    textField.text = text;
    textField.x = (Main.SCREEN_WIDTH - textField.width) / 2;

    graphics.beginFill(0x000000, 0.6);
    graphics.drawRect(0, 0, Main.SCREEN_WIDTH, textField.height);
    graphics.endFill();

    addChild(textField);

    btnSkip = new Bitmap(Assets.getBitmapData('assets/ui/btn_skip.png'));
    btnSkip.x = Main.SCREEN_WIDTH - btnSkip.width - 2;
    btnSkip.y = (height - btnSkip.height) / 2;
    btnSkip.alpha = 0.8;
    addChild(btnSkip);

    buttonMode = true;

    this.time = time == null ? text.split(' ').length * 0.5: time;
    this.callback = callback;
    this.onFinish = onFinish;

    addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
    addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
    addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
  }

  function onMouseOver(e: MouseEvent) {
    btnSkip.alpha = 1;
  }

  function onMouseOut(e: MouseEvent) {
    btnSkip.alpha = 0.8;
  }

  function onMouseUp(e: MouseEvent) {
    done();
  }

  function done() {
    onFinish();
    if(callback != null) {
      callback();
    }
  }

  override public function update(delta: Float) {
    super.update(delta);

    if(time <= 0) {
      done();
    } else {
      time -= delta;
    }
  }
}
