extends Control

@onready var livelabel: Label = $Panel/HBoxContainer4/HBoxContainer3/Label
@onready var coinlabel: Label = $Panel/HBoxContainer4/HBoxContainer/Label


@onready var stickspawner: Button = $Panel/HBoxContainer4/HBoxContainer4/Button2
const STICK_TRAP = preload("res://Game/Traps/stick_trap.tscn")

@onready var minespawner: Button = $Panel/HBoxContainer4/HBoxContainer4/Button3
const MINE = preload("res://Game/Traps/mine.tscn")

@onready var wallspawner: Button = $Panel/HBoxContainer4/HBoxContainer4/Button4
const WALL = preload("res://Game/Traps/wall.tscn")

@onready var archertowerspawn: Button = $Panel/HBoxContainer4/HBoxContainer2/Button2
const ARCHER_TOWER = preload("res://Game/Towers/archer_tower.tscn")

@onready var wizardtowerspawn: Button = $Panel/HBoxContainer4/HBoxContainer2/Button3
const WIZARD_TOWER = preload("res://Game/Towers/wizard_tower.tscn")

@onready var mortartowerspawn: Button = $Panel/HBoxContainer4/HBoxContainer2/Button4
const MORTAR_TOWER = preload("res://Game/Towers/mortar_tower.tscn")

@onready var delete_tower_button: Button = $Panel/HBoxContainer4/HBoxContainer5/Button4
const DELETER = preload("res://Game/Accesories/deleter.tscn")

var lives = 0
var originallives = 0
var coins = 0
var save_path = "user://map_scores.save"
var map_scores = {}

var SFX_loudness = 1.0
var master_volume = 1.0
var music_volume_raw = 1.0

func _ready() -> void:
	get_node("pausemenu").hide()
	get_node("pausemenu").z_index = 5
	get_node("GameOver").hide()
	get_node("GameOver").z_index = 5
	get_node("GameWon").hide()
	get_node("GameWon").z_index = 5
	get_node("Panel").show()
	get_node("Panel").z_index = 5
	get_node("WaveCounter").show()
	get_node("WaveCounter").z_index = 5
	
	stickspawner.connect("button_up", Spawn_Stick)
	stickspawner.tooltip_text = "Cost: 30\nReturn: 5"
	
	minespawner.connect("button_up", Spawn_Mine)
	minespawner.tooltip_text = "Cost: 40\nReturn: 10"
	
	wallspawner.connect("button_down", Spawn_Wall)
	wallspawner.tooltip_text = "Cost: 60\nReturn: 0"
	
	archertowerspawn.connect("button_up", Spawn_Archer)
	archertowerspawn.tooltip_text = "Cost: 120\nReturn: 60"
	
	wizardtowerspawn.connect("button_up", Spawn_wizard)
	wizardtowerspawn.tooltip_text = "Cost: 100\nReturn: 30"
	
	mortartowerspawn.connect("button_up", Spawn_Mortar)
	mortartowerspawn.tooltip_text = "Cost: 160\nReturn: 80"
	
	delete_tower_button.connect("button_up", Spawn_Deleter)
	
	var file = FileAccess.open(save_path, FileAccess.READ)
	if file:
		map_scores = file.get_var()
		file.close()
		
	var config = ConfigFile.new()
	var err = config.load("user://settings.cfg")
	if err == OK:
		var master_volume_raw = config.get_value("audio", "master_volume", 100.0)
		master_volume = clamp(master_volume_raw / 100.0, 0.0, 1.0)
		var sfx_volume_raw = config.get_value("audio", "sfx_volume", 100.0)
		SFX_loudness = clamp(sfx_volume_raw / 100.0, 0.0, 1.0)
		var music_volume_raw = config.get_value("audio", "music_volume", 100.0)
		SFX_loudness = clamp(sfx_volume_raw / 100.0, 0.0, 1.0)
	self.get_node("HealthLostAudio").volume_db = linear_to_db(master_volume * SFX_loudness)
	self.get_node("GameOverAudio").volume_db = linear_to_db(master_volume * music_volume_raw)
	self.get_node("VictoryAudio").volume_db = linear_to_db(master_volume * music_volume_raw)
	
func _process(delta : float)-> void:
		coinlabel.text = "Coins: " + str(coins)
		livelabel.text = "Lives: " + str(lives)
		if lives <= 0:
			GameOver()
	
func set_Lifes(amount) -> void:
	lives = amount
	originallives = amount

func get_Lifes():
	return lives
	
func Update_Lifes(amount) -> void:
	lives += amount
	if amount < 0:
		get_node("HealthLostAudio").play()

func Update_waves(wavecount) -> void:
	get_node("WaveCounter/HBoxContainer/Label").text = "Current wave: "+ str(wavecount)
	
func Update_Coins(amount) -> void:
	coins += amount
	
func Spawn_Stick() -> void:
	if coins >= 30:
		coins -= 30
		var stick = STICK_TRAP.instantiate()
		stick.name = "StickTrap-" + str(randi())
		get_parent().add_child(stick)

func Spawn_Mine() -> void:
	if coins >= 40:
		coins -= 40
		var mine = MINE.instantiate()
		mine.name = "Mine-" + str(randi()) 
		get_parent().add_child(mine)

func Spawn_Wall() -> void:
	if coins >= 60:
		coins -= 60
		var wall = WALL.instantiate()
		wall.name = "Wall-" + str(randi())
		get_parent().add_child(wall)

func Spawn_Archer() -> void:
	if coins >= 120:
		coins -= 120
		var tower = ARCHER_TOWER.instantiate()
		tower.name = "ArcherTower-" + str(randi())
		get_parent().add_child(tower)
	
func Spawn_wizard() -> void:
	if coins >= 100:
		coins -= 100
		var tower = WIZARD_TOWER.instantiate()
		tower.name = "WizardTower-" + str(randi())
		get_parent().add_child(tower)
	
func Spawn_Mortar() -> void:
	if coins >= 160:
		coins -= 160
		var tower = MORTAR_TOWER.instantiate()
		tower.name = "MortarTower-" + str(randi())
		get_parent().add_child(tower)

func Spawn_Deleter() -> void:
	var deleter = DELETER.instantiate()
	get_parent().add_child(deleter)


func _unhandled_input(event):
	if event is InputEventKey:
		if event.pressed and event.keycode == KEY_ESCAPE:
			get_node("pausemenu").show()
			get_node("Panel").hide()
			for i in get_parent().get_parent().get_children():
				if i.name.contains("Path2D"):
					for ii in i.get_children():
						ii.get_children()[0].set_process(false)
				
			for i in get_parent().get_children():
				if i.name != "sidepanel":
					i.set_process(false)
				var timer_node = i.get_node("Timer") if i.has_node("Timer") else null
				if timer_node:
					timer_node.stop()

				
			get_parent().get_parent().get_node("Timer").stop()


func GameOver() -> void:
	get_node("Panel").hide()
	get_node("GameOver").show()
	for i in get_parent().get_parent().get_children():
				if i.name.contains("Path2D"):
					for ii in i.get_children():
						ii.get_children()[0].set_process(false)
		
	for i in get_parent().get_children():
		if i.name != "sidepanel":
			i.set_process(false)
		var timer_node = i.get_node("Timer") if i.has_node("Timer") else null
		if timer_node:
			timer_node.stop()
	get_parent().get_parent().get_node("MusicPlayer").PauseAudio()
	get_node("GameOverAudio").play()

func GameWon() -> void:
	get_node("Panel").hide()
	get_node("GameWon").show()
	
	var map_name = get_parent().get_parent().name
	var new_score = int((lives / originallives) * 10)
	
	var file
	var old_scores = {}
	
	# Try to load old scores if file exists
	if FileAccess.file_exists(save_path):
		file = FileAccess.open(save_path, FileAccess.READ)
		if not file.eof_reached():
			old_scores = file.get_var()
		file.close()
	
	var old_score = old_scores.get(map_name, 0)
	if new_score >= old_score:
		old_scores[map_name] = new_score
		file = FileAccess.open(save_path, FileAccess.WRITE)
		file.store_var(old_scores)
		file.close()
	
	get_parent().get_parent().get_node("MusicPlayer").PauseAudio()
	get_node("VictoryAudio").play()



func _on_button_3_pressed() -> void:
	get_node("pausemenu").hide()
	get_node("Panel").show()
	for i in get_parent().get_parent().get_children():
				if i.name.contains("Path2D"):
					for ii in i.get_children():
						ii.get_children()[0].set_process(true)
		
	for i in get_parent().get_children():
		if i.name != "sidepanel":
			i.set_process(true)
		var timer_node = i.get_node("Timer") if i.has_node("Timer") else null
		if timer_node:
			timer_node.start()

	get_parent().get_parent().get_node("Timer").start()


func _on_button_2_pressed() -> void:
	get_tree().reload_current_scene()
	

func _on_button_pressed() -> void:
	get_tree().change_scene_to_file("res://Game/Menu/mapselector.tscn")
