extends StateMachine

onready var anim_player = parent.get_node("AnimationPlayer")
onready var laserpoint: Sprite = parent.get_node("Laserpoint")

# Adds the intial states
func _ready():
	add_state("deactivated")
	add_state("searching")
	add_state("hunting")
	add_state("locking")
	add_state("shooting")
	state = states.searching
	set_state(states.searching)
	anim_player.play("Turret Rotation")


# Calls the parent behaviours according to state
func _state_logic(_delta):
	var state_action_ref = "handle_deactivated_state"
	match self.state:
		"deactivated":
			state_action_ref = funcref(self, "handle_deactivated_state")
		"searching":
			state_action_ref = funcref(self, "handle_searching_state")
		"locking":
			state_action_ref = funcref(self, "handle_locking_state")
		"shooting":
			state_action_ref = funcref(self, "handle_shooting_state")
		_:
			state_action_ref = funcref(self, "handle_deactivated_state")
			print("don't panik")

	state_action_ref.call_func()


func handle_searching_state():
	parent.searching()


# Locking is intialized once when starting
# While the locking is handled by a Time/Turret, this method just passes
func handle_locking_state():
	pass


func handle_shooting_state():
	parent.shooting()


# Determines which state should be active at the moment
func _get_transition(_delta):
	# TODO why only this way?
	parent.get_node("StateLabel").text = self.state
	var new_state
	if parent.is_tracking_prey() && self.state == "searching":
		laserpoint.visible = false
		new_state = "locking"
	# TODO Helper function with null check and reference check
	if !parent.is_tracking_prey() && self.state == "shooting":
		laserpoint.visible = true
		new_state = "searching"
	if self.state == "locking" && parent.is_locked_on_target():
		laserpoint.visible = false
		new_state = "shooting"
	if new_state != self.state:
		return new_state

	return null


func _enter_state(new_state, old_state):
	if new_state == "shooting" && old_state == "locking":
		parent.get_node("FiringRateTimer").start()
	if new_state == "locking" && old_state == "searching":
		parent.start_locking()
		anim_player.stop()
	if new_state == "searching" && old_state == "shooting":
		# TODO Time for returning to 0 degrees is always the same 
		# Implement this using a tween
		parent.get_node("FiringRateTimer").stop()
		# TODO Go back to the tutorials and look for where to implement the animation queues and triggers
		anim_player.play("Turret Returning")
		anim_player.queue("Turret Rotation")
	pass


func _exit_state(old_state, new_state):
	pass
