extends CanvasLayer

var player: Player

var max_time: float = 15*60		# 15 minutes
var current_time: float
@export var countdown = true;

@onready var xp_bar = $XpBar 
@onready var xp = 0
@onready var xp_to_lvl_up = 3
var xp_to_next = 3
@onready var choose_upgrage = $Container;
@onready var upgrade_buttons = [$Container/updrage1, $Container/upgrade2, $Container/upgrade3]
signal upgrade_signal(upgrade_type: String)
var upgrades = [
	{
		'title': "DAMAGE",
		'description': "Add 0.5 damage to your weapon",
		'signal': 'damage_up'
	},
	{
		'title': "FIRE RATE",
		'description': "Increase fire rate by 15%",
		'signal': 'fire_rate_up'
	},
	{
		'title': "MAX HEALTH",
		'description': "Increase max health by 2.",
		'signal': 'max_health_up'
	},
	{
		'title': "HEAL",
		'description': "Heal you to full health",
		'signal': 'heal'
	},
	{
		'title': "MOVEMENT SPEED",
		'description': "Increase movement speed by 20%",
		'signal': 'movement_speed_up'
	},
	{
		'title': "STAMINA",
		'description': "Increase stamina by 35%\nIncrease stamina regen by 20%",
		'signal': 'stamina_up'
	},
]

# Called when the node enters the scene tree for the first time.
func _ready():
	current_time = max_time;
	player = get_tree().get_first_node_in_group("Player");
	
	update_timebar();
	update_xpbar();

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta):
	if countdown:
		change_time_value(- _delta);
	

func update_timebar():
	$ProgressBar.value = int(1000*current_time/max_time);

func update_xpbar():
	xp_bar.value = int(1000.0*xp/float(xp_to_lvl_up));

func change_time_value(by_value: float):
	current_time = clamp(current_time + by_value, 0, max_time)
	if current_time < 0.1:
		player._on_health_death();
	update_timebar();
	
	
func get_difficulty_multiplayer():
	return (max_time - current_time) / max_time


func send_upgrade(upgrade):
	upgrade_signal.emit(upgrade['signal'])
	choose_upgrage.visible = false
	get_tree().paused = false


func add_xp(added):
	xp += added
	if xp >= xp_to_lvl_up:
		get_tree().paused = true
		xp = 0
		xp_to_lvl_up += xp_to_next
		choose_upgrage.visible = true
		upgrades.shuffle()
		for i in range(3):
			upgrade_buttons[i].text = upgrades[i]['title'] + '\n' + upgrades[i]['description']
	update_xpbar()
		


func _on_updrage_1_pressed():
	send_upgrade(upgrades[0])


func _on_upgrade_2_pressed():
	send_upgrade(upgrades[1])


func _on_upgrade_3_pressed():
	send_upgrade(upgrades[2])
