extends Node2D

export var hp : int = 3 # Number of hits before dying
onready var fish = get_node("/root/Tank/Fish")
var moving = true
var dest_counter : int = 0
var next_dest = 60
var destination : Vector2

func _ready():
	print("I liiiiive...!")


func _process(delta: float) -> void:
	$SwordPivot.rotation_degrees += 1
	
	if destination:
		var v = get_global_mouse_position() - global_position
		var angle = v.angle() + deg2rad(270)
#		if global_position.x < get_global_mouse_position().x:
#			$AnimatedSprite.flip_v = false
#		else:
#			$AnimatedSprite.flip_v = true
		if rad2deg(angle) < 180 or rad2deg(angle) > 360:
			$AnimatedSprite.flip_v = true
		else:
			$AnimatedSprite.flip_v = false
		var rotation_speed = PI * 0.75 # PI = 180 degrees
		var angle_delta = rotation_speed * delta
		angle = lerp_angle(global_rotation, angle + 1.57, 1.0)
		angle = clamp(angle, global_rotation - angle_delta, global_rotation + angle_delta)
		global_rotation = angle


func _select_destination() -> Vector2:
	var dest = Vector2(rand_range(200, 1500), rand_range(200, 880))
	return dest


func _on_SwordHitbox_area_entered(area: Area2D) -> void:
	if area.is_in_group("Fish"):
		fish.belly_up("Piranha")


func _on_Blindzone_area_entered(area: Area2D) -> void:
	if area.is_in_group("Fish"):
		moving = false
		$TweenSwim.stop_all()


func _on_Blindzone_area_exited(area):
	if area.is_in_group("Fish"):
		moving = true


func _on_Timer_timeout() -> void:
	#destination.x = move_toward(position.x, fish.get_global_position().x)
	#destination.y = move_toward(position.y, fish.get_global_position().y)
	destination.x = move_toward(global_position.x, get_global_mouse_position().x, 100)
	destination.y = move_toward(global_position.y, get_global_mouse_position().y, 100)
#	if dest_counter >= next_dest:
#		destination = _select_destination()
#		next_dest = rand_range(60,1200) # second number lower = move more frequently
#		dest_counter = 0
#	else:
#		dest_counter +=1
	if moving:
		$TweenSwim.interpolate_property(self, "position", position, destination, 0.85, Tween.TRANS_EXPO, Tween.EASE_OUT) #number lower = faster
		$TweenSwim.start()
