extends KinematicBody2D

signal state_changed(state)
signal direction_changed(new_direction)
signal position_changed(new_position)
signal died

export(String) var weapon_path = ""

var state = 0
var weapon = null

var _transitions = {}


func _ready() -> void:
	$Health.connect("health_changed", self, "_on_Health_health_changed")
	if not weapon_path:
		return
	var weapon_node = load(weapon_path).instance()
	
	$WeaponSpawn.add_child(weapon_node)
	weapon = $WeaponSpawn.get_child(0)
	self.connect("direction_changed", weapon, "change_direction")
	weapon.connect("attack_finished", self, "attack_animation_finished")


func change_state(event) -> void:
	var transition = [state, event]
	if not transition in _transitions:
		return
		
	state = _transitions[transition]
	enter_state()
	
	emit_signal("state_changed")


func enter_state() -> void:
	pass


func take_damage(source, amount: int) -> void:
	if self.is_a_parent_of(source):
		return
	$Health.take_damage(amount)


func _on_Health_health_changed(new_health: int) -> void:
	print (new_health)
	if new_health == 0:
		emit_signal("died")
