extends Node2D

export var hp : int = 3 # Number of hits before dying
export var dash_duration : int = 2 # Duration of charge tween in seconds
onready var fish = get_node("/root/Tank/Fish")
var charging = false



func _ready():
	$ChargeTimer.start()
	$Sprite.flip_h = true


func _process(delta: float) -> void:
	var v
	v = fish.get_global_position() - global_position
	var angle = v.angle() + deg2rad(270)
	if rad2deg(angle) < 180 or rad2deg(angle) > 360:
		if not charging:
			$Sprite.flip_v = true
	elif not charging:
		$Sprite.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)
	if not charging:
		global_rotation = angle


func _on_ChargeTimer_timeout() -> void:
	var destination = $ChargeDestination.get_global_position()
	print("destination=" + str(destination))
	destination.x = clamp(destination.x, 200, 1720)
	destination.y = clamp(destination.y, 200, 880)
	print("clamped destination=" + str(destination))
	print("position=" + str(position))
	print("global_pos=" + str(global_position))
	$Tween.interpolate_property(self, "position", global_position, destination, dash_duration, Tween.TRANS_EXPO, Tween.EASE_IN)
	$Tween.start()
	charging = true
	yield($Tween, "tween_completed")
	charging = false
	$ChargeTimer.start()


func _on_Hurtbox_area_entered(area: Area2D) -> void:
	if area.is_in_group("Fish"):
		if fish.electrified:
			fish.belly_up("a concussion")


func _on_Hitbox_area_entered(area: Area2D) -> void:
	if area.is_in_group("Fish"):
		if fish.electrified:
			hp-=1 #below is flash feedback on hit
			$TweenColor.interpolate_property(self, "modulate", modulate, Color(0,0,0,1), .085)
			$TweenColor.start()
			yield($TweenColor, "tween_completed")
			$TweenColor.interpolate_property(self, "modulate", modulate, Color(1,1,1,1), .085)
			$TweenColor.start()
			if hp < 1: # kill angler
				_death()


func _death():
	$ChargeTimer.stop() #stop charging when dead
	$Sprite.flip_v = true
	charging = true #hack to stop rotating
	$Tween.interpolate_property(self, "position", get_global_position(),Vector2(get_global_position().x,100), dash_duration, Tween.TRANS_LINEAR, Tween.EASE_IN)
	# probably replacing his eyes with X_X's SKIP DO THIS
	$Tween.start()
