extends KinematicBody2D
class_name Player
var Bullet = preload("res://Bullet.tscn")

signal ammo_changed(ammo)
signal hp_changed(hp)
signal player_dead
signal player_hurt
signal shot_fired

func is_player() -> bool:
	return true

var input_vec = Vector2.ZERO
var last_dir = Vector2.ZERO
var ammo : int = 0
var max_hp : int = 5
var hp : int = 5

const SHOOT_COOLDOWN = 1
var shoot_cooldown_remaining : float = 0.0

onready var sprite = $AnimatedSprite

func _ready():
	pass

func is_type(type):
	return type == "Player" or .is_type(type)

func heal(amount : int):
	hp += amount
	if hp > max_hp:
		hp = max_hp
	emit_signal("hp_changed", hp)

func take_damage(dmg : int):
	hp -= dmg
	if hp <= 0:
		hp = 0
		emit_signal("player_dead")
	emit_signal("hp_changed", hp)
	emit_signal("player_hurt")

func get_type():
	return "Player"

func pick_up(p_ammo):
	ammo += p_ammo
	emit_signal("ammo_changed", ammo)

func fire():
	var bullet = Bullet.instance()
	bullet.global_position = self.global_position
	bullet.init(last_dir)
	get_parent().add_child(bullet)
	ammo -= 1
	emit_signal("ammo_changed", ammo)
	shoot_cooldown_remaining = SHOOT_COOLDOWN
	emit_signal("shot_fired")

func _process(delta):
	if !is_alive():
		return
	shoot_cooldown_remaining -= delta
	if shoot_cooldown_remaining < 0.0:
		shoot_cooldown_remaining = 0.0
	input_vec = Vector2.ZERO
	if Input.is_action_pressed("ui_down"):
		input_vec.y = 1
	if Input.is_action_pressed("ui_up"):
		input_vec.y = -1
	if Input.is_action_pressed("ui_right"):
		input_vec.x = 1
	if Input.is_action_pressed("ui_left"):
		input_vec.x = -1
	if input_vec != Vector2.ZERO:
		last_dir = input_vec.normalized()
	
	if Input.is_action_just_pressed("ui_accept"):
		if shoot_cooldown_remaining <= 0.0 and ammo > 0:
			fire()
	
	if input_vec.x < 0:
		sprite.animation = "side"
		sprite.flip_h = true
	elif input_vec.x > 0:
		sprite.animation = "side"
		sprite.flip_h = false
	
	if input_vec.y < 0:
		sprite.animation = "up"
	elif input_vec.y > 0:
		sprite.animation = "down"
	
func _physics_process(delta):
	move_and_slide(input_vec.normalized() * 100, Vector2.UP)

func is_alive() -> bool:
	return hp > 0
