package game.locations;

import base.GameSprite;

import openfl.events.Event;
import openfl.events.MouseEvent;
import openfl.display.Bitmap;
import openfl.Assets;

class Interactive extends GameSprite {
  public var hint: String = null;
  public var useTimes: Null<Int> = null;
  public var actionable(default, set): Bool;
  public var inAction(default, set): Bool = false;
  public var gotoFade: Bool = false;

  var gotoLocation: Class<Location> = null;
  var hints: Array<String> = null;
  var soundEffect: String = null;

  public function new(
      ?actionable: Bool = true,
      ?useTimes: Null<Int> = null,
      ?gotoLocation: Class<Location> = null,
      ?hints: Array<String> = null,
      ?soundEffect: String = null
    ) {
    super();
    this.actionable = actionable;
    this.useTimes = useTimes;
    this.gotoLocation = gotoLocation;
    this.hints = hints;
    this.soundEffect = soundEffect;
  }

  public function initBitmap(asset: String, center: Bool = false): Bitmap {
    var bitmap: Bitmap = new Bitmap(Assets.getBitmapData(asset));

    if(center) {
      bitmap.x = -bitmap.width / 2;
      bitmap.y = -bitmap.height / 2;
    }

    addChild(bitmap);
    return bitmap;
  }

  function onMouseDown(e: MouseEvent) {
    if(soundEffect != null) {
      Game.currentGame.playSound(soundEffect);
    }

    inAction = true;
    if(useTimes != null)
      useTimes--;
    action();
  }

  function onMouseOver(e: MouseEvent) {
  }

  function onMouseOut(e: MouseEvent) {
  }

  public function action() {
    inAction = false;

    if(gotoLocation != null) {
      Game.currentGame.setLocation(gotoLocation, gotoFade);
    }

    if(hints != null) {
      Game.currentGame.sayRandom(hints);
    }

    dispatchEvent(new Event('action'));
  }

  function set_inAction(value: Bool): Bool {
    if(value) {
      actionable = false;
    } else {
      if(((useTimes != null) && (useTimes > 0)) || (useTimes == null)) {
        actionable = true;
      }
    }

    return inAction = value;
  }

  function set_actionable(value: Bool): Bool {
    if(value) {
      buttonMode = true;
      mouseEnabled = true;
      addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
      addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
      addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
    } else {
      buttonMode = false;
      mouseEnabled = false;
      removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
      removeEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
      removeEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
    }

    return actionable = value;
  }
}
