class_name Player extends "res://scenes/spaceShip/spaceShip.gd"

@onready var timeGhostScene = preload("res://scenes/spaceShip/timeGhost/timeghost.tscn")

@onready var dashCooldown = $dashCooldown
@onready var selfHealTimer = $selfHealTimer
@onready var selfHealCountdownTimer = $selfHealCountdownTimer

@onready var progressBarHealth = $Camera2D/CanvasLayer/Control/VBoxContainer/HealthUi/ProgressBarHealth
@onready var progressBarSpeed = $Camera2D/CanvasLayer/Control/VBoxContainer/SpeedUi/ProgressBarSpeed
@onready var progressBarDashCooldown = $Camera2D/CanvasLayer/Control/VBoxContainer/DashCooldownUi/ProgressBarDashCooldown
@onready var progressBarWeaponCooldown = $Camera2D/CanvasLayer/Control/VBoxContainer/WeaponCooldown/ProgressBarWeaponCooldown
@onready var labelWaveInfo = $Camera2D/CanvasLayer/Control/HBoxContainer/HBoxContainer/LabelWaveInfo
@onready var labelWaveEnemiesInfo = $Camera2D/CanvasLayer/Control/HBoxContainer/HBoxContainer2/LabelWaveEnemiesInfo
@onready var labelWaveDestroyedInfo = $Camera2D/CanvasLayer/Control/HBoxContainer/HBoxContainer3/LabelWaveDestroyedInfo
@onready var upgradeChooser = $Camera2D/CanvasLayer/Control/UpgradeChooser

@onready var hit = $hit
@onready var input = $Camera2D/CanvasLayer/Control/Input

@export var spawnDistance: int = 5000

var maxSpeedMult: float = 3
var maxAcceleration: float = 1
var speedMult: float = 1
var damageMult: float = 1
var dashUnlocked: bool = false
var strifeUnlocked: bool = false
var selfHealUnlocked: bool = false


func _ready() -> void:
	if Globals.touchscreen:
		input.show()
	progressBarHealth.max_value = maxHealth
	progressBarSpeed.max_value = speed / 2
	progressBarDashCooldown.max_value = dashCooldown.wait_time
	randomize()
	changeWeapon(SHOTGUN)
	progressBarWeaponCooldown.max_value = weapon.cooldown
	shortInvincibility()
	await get_tree().create_timer(Globals.currentDelay).timeout
	addGhost()
	newUpgrade()
	Globals.waveComplete.connect(newUpgrade)
	

func _physics_process(delta: float) -> void:
	#if Input.is_action_pressed("attack"):
		#attack()
	#
	#look_at(get_global_mouse_position())
	#rotation += PI / 2
	#var direction = Vector2.UP.normalized().rotated(rotation) * Input.get_action_strength("moveForward")
	##Input.get_vector("moveForward", "moveBackward").normalized().rotated(rotation)
	#if Input.is_action_just_pressed("dash") and dashCooldown.is_stopped():
		#dash()
	#velocity = velocity.lerp(direction * speed, acceleration * delta)
	#move_and_slide()
	#if timeGhost != null:
		#moveTimeGhost(global_position, rotation)
		
	if Input.is_action_pressed("attack"):
		attack()
	var controllerDirection = Input.get_vector("lookLeft", "lookRight", "lookForward", "lookDown")
	controllerDirection
	if controllerDirection == Vector2.ZERO:
		look_at(get_global_mouse_position())
	else:
		look_at(global_position+controllerDirection)
	rotation += PI / 2
	var direction: Vector2
	#if strifeUnlocked:
		#direction = Input.get_vector("moveLeft", "moveRight", "moveForward", "moveBackward").normalized().rotated(rotation)
	if Globals.touchscreen:
		if Input.is_action_pressed("touchscreenForward"):
			direction = Vector2.UP.normalized().rotated(rotation) * Input.get_action_strength("touchscreenForward")
	else:
		direction = Vector2.UP.normalized().rotated(rotation) * Input.get_action_strength("moveForward")
	if Input.is_action_just_pressed("dash") and dashCooldown.is_stopped() and dashUnlocked:
		dash()
	#if Input.is_action_pressed("moveForward") or Input.is_action_pressed("moveLeft") or Input.is_action_pressed("moveRight"):
	if Input.is_action_pressed("moveForward") or Input.is_action_pressed("touchscreenForward"):
		velocity = velocity.lerp(direction * speed * speedMult, 1 * delta)
	move_and_slide()
	if timeGhost != null:
		moveTimeGhost(global_position, rotation)
	
	setInterface()

func _on_hurt_area_hurt(amount: int) -> void:
	damage(amount)
	hit.play()
	$Camera2D.shake(0.5, 5.0)
	if selfHealUnlocked:
		selfHealTimer.stop()
		selfHealCountdownTimer.start()

func dash():
	shortInvincibility()
	dashCooldown.start()
	global_position += Vector2.UP.rotated(rotation) * 1000

func getRandomSpawnPointPosition() -> Vector2:
	var rng = RandomNumberGenerator.new()
	return global_position + Vector2.UP.rotated(deg_to_rad(rng.randi_range(0, 360))) * spawnDistance

func addGhost():
	var _timeGhost = timeGhostScene.instantiate()
	get_tree().get_first_node_in_group("timeGhostPool").add_child(_timeGhost)
	addTimeGhost(_timeGhost)

func unlockDash():
	dashUnlocked = true

func unlockStrife():
	strifeUnlocked = true



func _on_self_heal_countdown_timeout() -> void:
	selfHealTimer.start()

func _on_self_heal_timer_timeout() -> void:
	if health >= maxHealth:
		selfHealTimer.stop()
	else:
		heal(1)
		selfHealTimer.start()


func setInterface():
	if dashUnlocked:
		$Camera2D/CanvasLayer/Control/VBoxContainer/DashCooldownUi.visible = true
	progressBarHealth.value = Globals.getPlayer().health
	progressBarSpeed.value = getVelocityMedian()
	if dashCooldown.is_stopped():
		progressBarDashCooldown.value = 0
	else:
		progressBarDashCooldown.value = dashCooldown.wait_time - dashCooldown.time_left
	
	if weapon != null:
		progressBarWeaponCooldown.value = weapon.cooldownTimer.wait_time - weapon.cooldownTimer.time_left
	labelWaveInfo.text = str(Globals.currentWave)
	labelWaveEnemiesInfo.text = str(Globals.enemyCount)
	labelWaveDestroyedInfo.text = str(Globals.destroyedShips)

func getVelocityMedian() -> float:
	var _velocity = velocity
	if _velocity.x < 0:
		_velocity.x *= -1
	if _velocity.y < 0:
		_velocity.y *= -1
	return (_velocity.x + _velocity.y) / 2

func newUpgrade():
	get_tree().paused = true
	upgradeChooser.showUpgrades()

func addSpeedMult(mult: float):
	if speedMult * mult > maxSpeedMult:
		speedMult = maxSpeedMult
		Globals.removeSpeedUPgrade()
	else:
		speedMult *= mult


func switchToMinigun():
	changeWeapon(MINIGUN)
	progressBarWeaponCooldown.max_value = weapon.cooldown

func switchToShotgun():
	changeWeapon(SHOTGUN)
	progressBarWeaponCooldown.max_value = weapon.cooldown
	
func switchToRailgun():
	changeWeapon(RAILGUN)
	progressBarWeaponCooldown.max_value = weapon.cooldown
