class_name BattleCursorIcon extends ColorRect

# How often to blink in milliseconds.
const BLINK_RATE := 100

enum Mode {
  INACTIVE,
  ACTIVE,
  BLINKING
}

@export var battlePosition:BattleSingleton.BattlePosition = BattleSingleton.BattlePosition.LEFT_TOP_BACK:
  get():
    return battlePosition

  set(value):
    battlePosition = value
    _updatePosition()

@export var mode:Mode = Mode.INACTIVE

func _ready() -> void:
  _updatePosition()

func _process(_delta: float) -> void:
  if mode == Mode.INACTIVE:
    self.visible = false
    return
  elif mode == Mode.ACTIVE:
    self.visible = true
  elif mode == Mode.BLINKING:
    self.visible = Time.get_ticks_msec() % (BLINK_RATE * 2) < BLINK_RATE

func _updatePosition() -> void:
  # Walk up the tree until BattleScene is found.
  var battleScene:BattleScene = null
  var currentNode:Node = self.get_parent()
  while currentNode != null:
    if currentNode is BattleScene:
      battleScene = currentNode
      break
    currentNode = currentNode.get_parent()
  
  if battleScene == null:
    #push_error("BattleCursorIcon could not find BattleScene in parent nodes.")
    return

  var targetFighter:BattleFighterScene = battleScene.getFighterSceneAtPosition(battlePosition)
  if targetFighter == null:
    push_error("No BattleFighter found at battlePosition %s" % str(battlePosition))
    return

  # Convert the target fighter's global position to screen space position.
  var viewport:Viewport = get_viewport()
  var screenPos:Vector2 = viewport.get_camera_3d().unproject_position(targetFighter.global_transform.origin)
  self.position = screenPos
