extends Node2D

const UP_MAX_POS = -200
const UP_MIN_POS = 100
const DOWN_MAX_POS = 900
const DOWN_MIN_POS = 600

const MAX_BLINK_VARIATION = 50

@export var eyeUp: Sprite2D
var eyeUpPos = UP_MAX_POS

@export var eyeDown: Sprite2D
var eyeDownPos = DOWN_MIN_POS

var progress: float

@export var counter_text: Label
const MAX_TIME = 99

@export var start_time = 50
@export var decrease_speed = 0.5
var current_time: float

var timer_going = true

var enabled = false

@onready var cutscene = load("res://scenes/ending.tscn")

func _get_percentage() -> float:
	return inverse_lerp(MAX_TIME, 0, int(current_time))

func _quit_dialogue(time_to_add: int):
	current_time += (time_to_add * 2)
	current_time = clamp(current_time, 0, MAX_TIME)

# Called when the node enters the scene tree for the first time.
func _ready():
	DialogueManager.dialogue_finished.connect(_quit_dialogue)
	
	current_time = start_time;
	counter_text.text = ""
	
	progress = _get_percentage()
	
	eyeUpPos = lerp(UP_MAX_POS, UP_MIN_POS, progress)
	eyeDownPos = lerp(DOWN_MAX_POS, DOWN_MIN_POS, progress)

func enable():
	counter_text.text = str(int(current_time))
	enabled = true

var time = 0.0

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	time += delta
	
	var pos_offset = _sine_operation(time)
	
	_eye_pos_up(pos_offset)
	_eye_pos_down(pos_offset)
	
	if !enabled:
		return
	current_time -= decrease_speed * delta * int(timer_going)
	counter_text.text = str(int(current_time))
	progress = _get_percentage()
	
	eyeUpPos = lerp(UP_MAX_POS, UP_MIN_POS, progress)
	eyeDownPos = lerp(DOWN_MAX_POS, DOWN_MIN_POS, progress)
	
	if current_time <= 0.5:
		SceneTransition.change_scene(cutscene)

#t: time g: gap o: offset
func _sine_function(t: float, g: float, o: float) -> float:
	return sin(t*g+o)

func _sine_operation(t: float) -> float:
	return .25 * (
		_sine_function(t, 1, 4) +
		_sine_function(t, 2, 3) +
		_sine_function(t, 3, 2) +
		_sine_function(t, 4, 1)
	)

func _eye_pos_up(t: float):
	eyeUp.position.y = int(lerp(eyeUpPos - MAX_BLINK_VARIATION/2, eyeUpPos + MAX_BLINK_VARIATION/2, t) / 4.0) * 4

func _eye_pos_down(t: float):
	eyeDown.position.y = int(lerp(eyeDownPos + MAX_BLINK_VARIATION/2, eyeDownPos - MAX_BLINK_VARIATION/2, t) / 4.0) * 4
