extends CharacterBody2D

@export_group("Skins")
@export var CurrentSkin: CanvasTexture
@export var CurrentHat: CanvasTexture

const SPEED = 1000.0
const MOUSESPEED = 10.0

var Traveling = false

func teleport(location:Vector2 , direction:float = 1):
	position = location
	#scale = Vector2(direction,1)

# Change the skin on every sprite
func changeSkin(NewSkin:CanvasTexture,_NewHat:CanvasTexture = null):
	CurrentSkin = NewSkin
	if (_NewHat):
		CurrentHat = _NewHat
		
	for Sprite :Sprite2D in $Skeleton2D.get_children():
		if (Sprite.has_meta("Type") and Sprite.get_meta("Type") == "Skin"):
			Sprite.texture = CurrentSkin
		if (Sprite.has_meta("Type") and Sprite.get_meta("Type") == "Hat"):
			Sprite.texture = CurrentHat

func get_input():
	#TODO: Need to freeze the player while he is traveling
	var directionX = Input.get_axis("move_left", "move_right")
	var directionY = Input.get_axis("move_up", "move_down")
	var mouseDirectionX = Input.get_axis("mouse_left", "mouse_right")
	var mouseDirectionY = Input.get_axis("mouse_up", "mouse_down")
	#region Movement
	## Get the input direction and handle the movement/deceleration.
	if directionX :
		velocity.x = directionX * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
	if directionY:
		velocity.y = directionY * SPEED
	else:
		velocity.y = move_toward(velocity.y, 0, SPEED)
	#endregion
	var wantedMousePosition = get_viewport().get_mouse_position()+(Vector2(mouseDirectionX,mouseDirectionY)*MOUSESPEED)
	get_viewport().warp_mouse(wantedMousePosition)
	#region Animation
	if (directionX < 0):
		$Skeleton2D/root/Hips.set_scale(Vector2(1, 1))
	if (directionX > 0):
		$Skeleton2D/root/Hips.set_scale(Vector2(-1, 1))
	$AnimationTree.set("parameters/WalkRun/blend_position",max(abs(velocity.x),abs(velocity.y)))
	#endregion

func _physics_process(_delta):
	get_input()	
	move_and_slide()
