extends Area2D

signal pickup
signal hit

@export var speed = 300
var velocity = Vector2.ZERO
var screenSize = Vector2(480, 720)
# Called when the node enters the scene tree for the first time.
func start():
	set_process(true)
	position = screenSize / 2
	$AnimatedSprite2D.animation = "idle"

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	velocity = Vector2(0,0)
	if Input.is_action_pressed("ui_left"):
		print("Left arrow is pressed")
		velocity.x -= 1
		if Input.is_action_pressed("ui_up"):
			velocity.y -= 1
		elif Input.is_action_pressed("ui_down"):
			velocity.y += 1
		
	elif Input.is_action_pressed("ui_right"):
		print("Right arrow is pressed")
		velocity.x += 1
		if Input.is_action_pressed("ui_up"):
			velocity.y -= 1
		elif Input.is_action_pressed("ui_down"):
			velocity.y += 1
	elif Input.is_action_pressed("ui_up"):
		print("Up arrow is pressed")
		velocity.y -= 1
	elif Input.is_action_pressed("ui_down"):
		print("Down arrow is pressed")
		velocity.y += 1
	
	position += velocity * speed * delta
	
	position.x = clamp(position.x, 0, screenSize.x)
	position.y = clamp(position.y, 0, screenSize.y)
	
	#animation
	if velocity.length() > 0:
		$AnimatedSprite2D.animation = "run"
	else:
		$AnimatedSprite2D.animation = "idle"

	if velocity.x != 0:
		$AnimatedSprite2D.flip_h = velocity.x < 0

func die():
	$AnimatedSprite2D.animation = "hit"
	set_process(false)

func _on_area_entered(area):
	if area.is_in_group("fruits"):
		area.pickup()
		pickup.emit()
	if area.is_in_group("powerups"):
		area.pickup()
		pickup.emit()
	if area.is_in_group("obstacles"):
		hit.emit()
		die()
