extends Node2D

@export var nextlevel:PackedScene = null
@export var is_final_level:bool = false
@export var level_time = 5 
@onready var start = $Start
@onready var exit = $Exit
@onready var deathzone = $Deathzone
@onready var ui_layer = $UILayer

@onready var hud = $UILayer/HUD

var player = null
var time_left 
var timer_Node = null
var win = false

func _ready():
	player = get_tree().get_first_node_in_group("player")
	if player != null:
		player.global_position = start.get_spawn_pos()
	var traps = get_tree().get_nodes_in_group("traps")
	for trap in traps:
		#trap.connect("touchedPlayer", _on_trap_touched_player)
		trap.touchedPlayer.connect(_on_trap_touched_player)
	exit.body_entered.connect(_on_exit_body_entered)
	deathzone.body_entered.connect(_on_deathzone_body_entered)
	
	
	
	#Level timer, when zero reset level
	time_left = level_time
	hud.set_time_vlaue(time_left)
	timer_Node = Timer.new()
	timer_Node.name = "Level Timer"
	timer_Node.wait_time = 1
	timer_Node.timeout.connect(_on_level_timer_timeout)
	add_child(timer_Node)
	timer_Node.start()
	
func _on_level_timer_timeout():
	if win == false:
		time_left -= 1
		hud.set_time_vlaue(time_left)
		if time_left < 0:
			resetPlayer()
			time_left = level_time
			hud.set_time_vlaue(time_left)

func _process(delta):
	if Input.is_action_just_pressed("quit"): #ESC
		get_tree().quit()
	elif Input.is_action_just_pressed("reset"): #R
		get_tree().reload_current_scene()

func _on_deathzone_body_entered(body):
	resetPlayer()

func _on_trap_touched_player():
	resetPlayer()

func resetPlayer():
	player.velocity = Vector2.ZERO
	player.global_position = start.get_spawn_pos()
	time_left = level_time + 1

func _on_exit_body_entered(body):
	if body is player:
		if is_final_level || nextlevel != null:
			exit.animate()
			player.active = false
			win = true
			await get_tree().create_timer(1.5).timeout
			player.active = true
			if is_final_level:
				ui_layer.win_screen_show(true)
			else:
				get_tree().change_scene_to_packed(nextlevel)
