extends CharacterBody2D
class_name Player

var speed = 300.0
var hit_points: int = 3
var bullets: int = 6
var isReloading: bool = false
var dash_just_used: bool = false
signal died

@onready var animplayer = $AnimationPlayer
@onready var camera_remote_transform = $CameraRemoteTransform
@onready var shoot_raycast = $ShootRaycast
@onready var shoot_sound = $ShootSound
@onready var reload_sound = $ReloadSound
@onready var empty_sound = $EmptyGunSound
@onready var reload_timer = $ReloadTimer
@onready var animplayer_hurt = $AnimationPlayerHurt


@warning_ignore("unused_parameter")
func _process(delta: float) -> void:
	look_at(get_global_mouse_position())
	
	if Input.is_action_just_pressed("quit"):
		get_tree().quit()
		
	if Input.is_action_just_pressed("shoot") && isReloading == false:
		if bullets == 0:
			empty_sound.play()
			print("No more Bullets left!")
			
		else:
			shoot_sound.play()
			animplayer.play("shot_flare")
			bullets = bullets -1
			if shoot_raycast.is_colliding():
				var collider = shoot_raycast.get_collider()
				if collider is StaticBody2D:
					print("Shot a box!")
				elif collider is Enemy:
					print("Hit an Enemy!")
					var e = collider as Enemy
					e.player = self
					e.take_damage(1)
				
				
	if Input.is_action_just_pressed("reload") && isReloading == false && bullets != 6:
		isReloading = true
		reload_sound.play()
		#reload_timer.start()
		await get_tree().create_timer(3.0).timeout
		bullets = 6
		isReloading = false
		print("Reloaded!")
	
func dash():
	if dash_just_used != true:
		speed = 1000
		dash_just_used = true
		await get_tree().create_timer(0.2).timeout
		speed = 300
		await get_tree().create_timer(1).timeout
		dash_just_used = false

@warning_ignore("unused_parameter")
func _physics_process(delta: float) -> void:
	var move_dir = Vector2(Input.get_axis("move_left", "move_right"),
	Input.get_axis("move_up", "move_down"))
	if Input.is_action_just_pressed("move_dash") && dash_just_used == false:
		dash()
	if move_dir != Vector2.ZERO:
		velocity = speed * move_dir.normalized()
	else:
		velocity.x = move_toward(velocity.x, 0, speed)
		velocity.y = move_toward(velocity.y, 0, speed)
	
	move_and_slide()

func _on_hit_box_body_entered(body: Node2D) -> void:
	if body is Enemy:
		print("got hit!")
		died.emit()
		queue_free()
		
func take_damage(amount: int):
	if amount > 0:
		hit_points -= amount
		animplayer_hurt.play("Hurt")
		if hit_points <= 0:
			print(name +" died")
			died.emit()
			queue_free()
			
func get_bullets():
	return bullets
	
func get_hit_points():
	return hit_points
