extends RigidBody2D

export var poisoned_color : Color = Color(0,0.78,0,1)
var fish : Node
var direction
var projectile = false


func _ready():
	fish = get_node("/root/Tank/Fish")
	global_rotation_degrees = rand_range(0, 360)
	$AnimatedSprite.frame = choose([0,1,2])


func _on_Hitbox_area_entered(area: Area2D) -> void:
	if area.is_in_group("TankFloor"):
		$DissolveTimer.start()
		
	if not projectile and area.is_in_group("Fish") and not fish.invincible:
		if fish.poisoned == false and not fish.poison_mutation and modulate != Color(1,1,1,1): # Eat the pellet as poison
			print("A poison pellet has inflicted poison on the fish.")
			fish.poisoned = true
			visible = false
			$PoisonTimer.start()
			$TweenPoison.interpolate_property(area.get_parent(), "modulate", Color(1,1,1,1), poisoned_color, 2.0, Tween.TRANS_LINEAR, Tween.EASE_IN)
			$TweenPoison.start()
		elif fish.poison_mutation or get_parent().phase == get_parent().Phase.CLEAN: # Eat the pellet as ammo
			fish.reset_hunger()
			fish.pellets += 1
			#$TweenEat.interpolate_property(self, "position", position, get_node("/root/Tank/Fish/Positions/MouthInhale").get_global_position(), 0.5, Tween.TRANS_EXPO, Tween.EASE_IN, 0.5)
			$TweenEat.interpolate_property(self, "position", position, get_node("/root/Tank/Fish/Positions/Mouth").get_global_position(), 0.5, Tween.TRANS_EXPO, Tween.EASE_IN)
			$TweenEat.interpolate_property(self, "scale", scale, Vector2(0.1, 0.1), 0.5, Tween.TRANS_LINEAR, Tween.EASE_IN)
			$TweenEat.start()
			$Crunch.pitch_scale = rand_range(0.8, 1.2)
			$Crunch.play()
			yield($TweenEat, "tween_completed")
			queue_free()


static func choose(choices):
	return choices[randi() % choices.size()]


func _on_Timer_timeout() -> void:
	if fish:
		fish.belly_up("poison")


func _on_DissolveTimer_timeout() -> void:
	$TweenDissolve.interpolate_property(self, "modulate:a", modulate.a, 0, 3, Tween.TRANS_LINEAR, Tween.EASE_IN)
	$TweenDissolve.start()
	yield($TweenDissolve, "tween_completed")
	queue_free()
