extends KinematicBody2D

var velocity = Vector2(0,0)
var direction = Vector2(1,0)

export var player_number: int = 1

onready var movement_animations: AnimatedSprite = $AnimatedSprite

onready var movement_state_machine: Node = $Controllers/state_machine

onready var player_move_component = $Controllers/decision_component

onready var player_hurtbox = $Hurtbox/CollisionShape2D

onready var enemy_hitbox = $Hitbox/CollisionShape2D

onready var player_detection = $PlayerDetection

onready var gun = $Gun

func _ready() -> void:
	movement_state_machine.init(self, movement_animations, player_move_component)

func _physics_process(delta: float) -> void:
	movement_state_machine.process_physics(delta)
#	#TODO: So much hack
#	if direction.x != 0:
#		gun.set_scale( Vector2(direction.x,1))
	if direction.x < 0:
		var t = Transform2D()
		# Translation
		t.origin = Vector2(gun.offset_position.x * -1, gun.offset_position.y)
		gun.transform = t
		player_detection.cast_to = Vector2(-20,0)
		#var t2 = Transform2D.FLIP_Y
		#enemy_hitbox.transform = Transform2D.FLIP_Y
		$Hitbox.transform = Transform2D.FLIP_X
	elif direction.x > 0:
		var t = Transform2D()
		# Translation
		t.origin = Vector2(gun.offset_position.x, gun.offset_position.y)
		gun.transform = t
		player_detection.cast_to = Vector2(20,0)
		#enemy_hitbox.transform = Transform2D.IDENTITY
		$Hitbox.transform = Transform2D.IDENTITY

func _process(delta: float) -> void:
	movement_state_machine.process_frame(delta)
	player_move_component.current_state_name = movement_state_machine.current_state.name

func _on_AnimatedSprite_animation_finished():
	if movement_animations.frames.get_animation_loop(movement_animations.animation) == false:
		movement_state_machine.current_state.animation_index += 1

func set_hurtbox(enabled: bool):
	#player_hurtbox.disabled = enabled #nope
	player_hurtbox.set_deferred("disabled", !enabled) #WTF Apparently this is how to do it
	#$Hurtbox.monitoring = enabled #nope
	#$Hurtbox.set_deferred("monitoring", enabled) #works
	#$Hurtbox.monitoring = false #nope
	#$Hurtbox.set_monitoring(enabled) # Nope

func set_hitbox(enabled: bool):
	#player_hurtbox.disabled = enabled #nope
	enemy_hitbox.set_deferred("disabled", !enabled) #WTF Apparently this is how to do it


func shoot_projectile():
	var is_shooting = false
	is_shooting = gun.shoot(transform.x.x)


func _on_Hurtbox_body_entered(body):
	print("Body Ouch. (Enemy)",body)
	movement_state_machine.change_state($Controllers/state_machine/hurt)
