extends Node2D

@onready var spawntimer = $spawntimer
@onready var player = $Player
@onready var healthBar = $hud/healthbar
@onready var healthWhite = $hud/healthwhite
@onready var healthBg = $hud/healthbg
@onready var healthLabel = $hud/healthlabel
@onready var slowdown = $hud/slowdown
@onready var upgradesHUD = $hud/upgrades
@onready var goldupgradesHUD = $hud/goldupgrades
@onready var ff = $hud/ff
@onready var beep = $hud/beep
@onready var beep2 = $hud/beep2

@onready var waveBg = $hud/wavebg
@onready var waveBar = $hud/wavebar
@onready var waveLabel = $hud/wavetimerlabel
@onready var waveCountLabel = $hud/wavelabel

@onready var tilemap = $navigation/TileMapLayer
#func _ready() -> void:
	#

@onready var shooter = preload("res://assets/scenes/shooter.tscn")
@onready var bomber = preload("res://assets/scenes/walkingBomb.tscn")
@onready var upgradeUI = preload("res://assets/scenes/upgradeUI.tscn")

var healthLast = 0
var baked := false
var rooms = []

var ticks := 0
var tickToDel := 0

var currentWave := 1
var waveTimer := 15.0
var untilNewWave := 15.0

var upgradeUnlocksPerTick = {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: []}

# up, down, left, right
#var roomRules := [
	#[
		#[0, 1, 2, 3, 4, 5, 6, 7, 10], [], [1, 2, 3, 5, 6, 7], [1, 2, 3, 4, 5, 6]
	#],
	#[
		#
	#],
	#[
		#
	#],
	#[
		#
	#]
#]

@onready var patterns: Array[TileMapPattern] = []

func wfc():
	pass
	
func appendUpgrade(upgradeID : String):
	
	if randi_range(1,10) == 1:
		# gold upgrade
		
		var upgradeIDE = Globals.availableGoldUpgrade.pick_random()
		Globals.unlockedUpgrades[upgradeIDE] = Globals.unlockedUpgrades.get(upgradeIDE, 0) + 1
	
		var instantiated = upgradeUI.instantiate()
		instantiated.get_node("texture").texture = load(str("res://assets/images/upgrades/", upgradeIDE, ".png"))
		#instantiated.timer = Globals.UPGRADE_TIMERSTART
		instantiated.goldUpgrade = true
		instantiated.upgradeID = upgradeIDE
		#instantiated.get_node("animations").play("init")
		goldupgradesHUD.add_child(instantiated)
		
		$newupgrade/title.text = "[GOLD] " + upgradeIDE.capitalize().to_lower()
		$newupgrade/icon.texture = load(str("res://assets/images/upgrades/", upgradeID, ".png"))
		
		if Globals.goldUpgradeDescriptionOverrides.get(upgradeIDE, "") == "":
			$newupgrade/text.text = Globals.upgradeDescriptions[upgradeIDE]
		else:
			$newupgrade/text.text = Globals.goldUpgradeDescriptionOverrides[upgradeIDE]
		
		$newupgrade/animations.stop()
		$newupgrade/animations.play("newUpgrade")
		
		return
	
	#print(upgradeID)
	Globals.unlockedUpgrades[upgradeID] = Globals.unlockedUpgrades.get(upgradeID, 0) + 1
	#upgradeUnlocksPerTick[ticks].append(upgradeID)
	#TextureRect.new().texture.resource_path
	
	var modified := false
	for icon in upgradesHUD.get_children():
		if icon.upgradeID == upgradeID:
			icon.amount += 1
			modified = true
			break
	
	if not modified:
		var instantiated = upgradeUI.instantiate()
		instantiated.get_node("texture").texture = load(str("res://assets/images/upgrades/", upgradeID, ".png"))
		instantiated.timer = Globals.UPGRADE_TIMERSTART
		instantiated.upgradeID = upgradeID
		#instantiated.get_node("animations").play("init")
		upgradesHUD.add_child(instantiated)
	
	$newupgrade/title.text = upgradeID.capitalize().to_lower()
	$newupgrade/icon.texture = load(str("res://assets/images/upgrades/", upgradeID, ".png"))
	$newupgrade/text.text = Globals.upgradeDescriptions[upgradeID]
	
	$newupgrade/animations.stop()
	$newupgrade/animations.play("newUpgrade")

func _ready():
	
	#appendUpgrade("stopwatch")
	#appendUpgrade("shotgun")
	
	for i in range(11):
		patterns.append(tilemap.tile_set.get_pattern(i))
		
	for y in range(-10,10):
		for x in range(-10,10):
			if randi_range(1, 100) < 50:
				tilemap.set_pattern(Vector2i(x * 5, y * 5), patterns[randi_range(0, 7)])
			else:
				tilemap.set_pattern(Vector2i(x * 5, y * 5), patterns[8])

	#tilemap.set_pattern(Vector2i(-12, -12), patterns[9])
	#tilemap.set_pattern(Vector2i(4, -12), patterns[9])
	#tilemap.set_pattern(Vector2i(-12, 4), patterns[9])
	#tilemap.set_pattern(Vector2i(4, 4), patterns[9])

	$navigation.bake_navigation_polygon()

var timer := 0.0

func _process(delta: float) -> void:
	waveTimer -= delta
	
	if player.health <= 0:
		Engine.time_scale = 1
		$hud/deathrect.modulate.a += (1 - $hud/deathrect.modulate.a) * delta
		
		if Input.is_action_just_pressed("shoot"):
			get_tree().change_scene_to_file("res://assets/scenes/mainMenu.tscn")
	
		return
	
	#appendUpgrade("shotgun")
	
	if not baked:
		timer += delta
		$bakewait/Label.text = "baking collisions"
		for i in range(int(timer)):
			$bakewait/Label.text += "."
		
		if timer >= 4: timer = 0
		
		return
		
	
	$bg.global_position = player.global_position - $bg.size / 2
	
	timer += delta / player.speedScale
	
	if player.transitioning:
		beep.pitch_scale = 1
	elif player.health < 15:
		beep.pitch_scale = 1 + 2 - (player.health / 15) * 2
	else:
		beep.pitch_scale = 1
	
	if player.newHealth == -1 and not player.transitioning: 
		player.health -= delta * player.speedScale * player.damageScale
	if healthLast != int(player.health): 
		beep.play()
		$hud/AnimationPlayer.play("secondBig")
	healthBar.size.x += (healthBg.size.x * (int(player.health) / 30.0) - healthBar.size.x) * 2 * delta
	waveBar.size.x += (waveBg.size.x * (int(waveTimer) / untilNewWave) - waveBar.size.x) * 3 * delta
	#healthWhite.size.x = healthBg.size.x * (int(player.health + 1) / 30.0)
	healthBar.color.r = 1 - (int(player.health) / 30.0)
	healthBar.color.g = (int(player.health) / 30.0)
	
	healthLabel.text = str(int(player.health), "s")
	waveLabel.text = str(int(waveTimer), "s")
	
	beep2.global_position = player.global_position
	
	if waveTimer < 0:
		untilNewWave *= 1.2
		waveTimer = untilNewWave
		currentWave += 1
		
		spawntimer.wait_time *= 0.9
		
		appendUpgrade(Globals.availableUpgrades.pick_random())
		
		waveCountLabel.text = str("wave ", currentWave)
		beep2.play()
	
	healthLast = int(player.health)
	slowdown.material.set_shader_parameter('saturation', player.grayscaleVal)
	#a

func _on_navigation_bake_finished() -> void:
	$bakewait.queue_free()
	baked = true
	timer = 0


func _on_spawntimer_timeout() -> void:
	var newEnemy = shooter.instantiate()
	newEnemy.health = 80 * pow(currentWave, 0.7)
	newEnemy.maxHealth = 80 * pow(currentWave, 0.7)
	newEnemy.wave = currentWave
	newEnemy.global_position = player.global_position + Vector2(randi_range(-500, 500), randi_range(-100, 100))
	get_node("enemies").add_child(newEnemy)

	if currentWave >= 3 and randi_range(1, 5) == 1:
		var thebomba = bomber.instantiate()
		thebomba.health = 200 * pow(currentWave, 0.7)
		thebomba.maxHealth = 200 * pow(currentWave, 0.7)
		thebomba.wave = currentWave
		thebomba.global_position = player.global_position + Vector2(randi_range(-500, 500), randi_range(-100, 100))
		get_node("enemies").add_child(thebomba)

func _on_player_transition_start(seconds: Variant) -> void:
	for enemy in get_node("enemies").get_children():
		enemy.moveback(max(seconds, enemy.ticks / 20))
		print("moveback1")
		
	#print(upgradeUnlocksPerTick, "\n", max(ticks - int(seconds) - 1,tickToDel))
	#for upgrade in upgradeUnlocksPerTick[max(ticks - int(seconds) - 1,tickToDel)]:
		#appendUpgrade(upgrade)


func _on_upgradetick_timeout() -> void:
	ticks += 1
	if upgradeUnlocksPerTick.get(ticks, [67]) == [67]: upgradeUnlocksPerTick[ticks] = []
	
	if ticks > 60:
		upgradeUnlocksPerTick.erase(tickToDel)
		tickToDel += 1
	
