extends Node2D

#enum { PLAYING, GOING_IN, INSIDE, COMING_OUT}
#var status = PLAYING

enum Phase { START, CLEAN, POISON, KNIFE, SQUID, HEATER, ANGLER, NEXT }
var phase = Phase.START


func _ready() -> void:
	randomize()
	modulate = Color(0,0,0,1)
	blackout()


func _input(event: InputEvent) -> void:
	if event is InputEventMouseButton and event.button_index == BUTTON_LEFT and event.pressed:
		$Fish.fire_pellet() # Fire a pellet if appropriate and able


static func random_position(area: CollisionShape2D) -> Vector2:
	var _topleft  : Vector2 = area.global_position - area.shape.extents
	var _botright : Vector2 = area.global_position + area.shape.extents
	var _x = rand_range(_topleft.x, _botright.x)
	var _y = rand_range(_topleft.y, _botright.y)
	return Vector2(_x, _y)


func _on_HazardTimer_timeout() -> void:
	if phase == Phase.CLEAN or phase == Phase.POISON:
		var poison_scene = load("res://Hazards/Poison/Poison.tscn")
		var poison = poison_scene.instance()
		if phase == Phase.CLEAN:
			poison.modulate = Color(1,1,1,1)
		add_child(poison)
		poison.position = random_position($HazardSpawner)


func blackout() -> void:
	if not phase == Phase.START:
		yield($Fish.go_inside(), "completed")
	if not modulate == Color(0,0,0,1):
		$TweenBlackout.interpolate_property(self, "modulate", modulate, Color(0,0,0,1), 2, Tween.TRANS_LINEAR, Tween.EASE_IN)
		$TweenBlackout.start()
		yield($TweenBlackout, "tween_completed")
	next_phase()
	$House/HouseEyes.visible = false
	$House/HouseRight.z_index = $House/HouseLeft.z_index
	print(phase)
	if phase == Phase.POISON:
		$SurvivePoisonTimer.start()
	if not phase == Phase.CLEAN:
		$Fish.position = $House/RightEntrance.get_global_position() + Vector2(0,-100)
		$Fish.global_rotation_degrees = 180
		$Fish/AnimatedSprite.flip_v = true
		$Fish.visible = true
		$Fish.destination = $House/LeftEntrance.get_global_position()+Vector2(0,-100)
		$Fish/TweenSwim.interpolate_property($Fish, "position", $Fish.get_global_position(), $House/LeftEntrance.get_global_position()+Vector2(0,-100), 2, Tween.TRANS_CUBIC, Tween.EASE_IN_OUT)
		$Fish/TweenSwim.start()
	$TweenBlackout.interpolate_property(self, "modulate", modulate, Color(1,1,1,1), 2, Tween.TRANS_LINEAR, Tween.EASE_IN)
	$TweenBlackout.start()
	yield($TweenBlackout, "tween_completed")
	$Fish.invincible = false


func next_phase() -> void:
	if phase == Phase.CLEAN: # Clean tank of pellets before poison phase
		var pellets = get_tree().get_nodes_in_group("Pellets")
		for pellet in pellets:
			pellet.queue_free()
	phase += 1


func _on_SurvivePoisonTimer_timeout() -> void:
	blackout()
