extends CharacterBody2D

@export var player_id = 0
@onready var sprite = $sprite
const SPEED = 150.0
const JUMP_VELOCITY = -300.0
@onready var snd_jmp = $jmp
var double_jump = 0
var coins = 0
var direction = 0

func _ready() -> void:
	randomize()
	if player_id == 0:
		sprite.modulate = Color.AQUA
	elif player_id == 1:
		sprite.modulate = Color.GREEN
	else:
		sprite.modulate = Color.from_hsv((randi() % 12) / 12.0, 1, 1)
	
func _physics_process(delta: float) -> void:
	# Add the gravity.
	if not is_on_floor():
		velocity += get_gravity() * delta
	
	direction = 0
	keyboard_inputs()
	gamepad_inputs()
	play_animations()
	
	velocity.x = direction * SPEED
	move_and_slide()

func keyboard_inputs():
	# Handle jump.
	if Input.is_action_just_pressed("jump") && is_on_floor():
		double_jump = 0
		snd_jmp.play()
		velocity.y = JUMP_VELOCITY
	elif Input.is_action_just_pressed("jump") && double_jump == 1:
		double_jump +=1
		snd_jmp.play()
		velocity.y = JUMP_VELOCITY

	if Input.is_action_just_released("jump") && double_jump == 0 :
		double_jump += 1
		
	if Input.is_action_pressed("left"):
		direction = -1
	elif Input.is_action_pressed("right"):
		direction = 1
		
func gamepad_inputs():
	# Handle jump.
	if Input.is_joy_button_pressed(player_id,JOY_BUTTON_B) && is_on_floor():
		double_jump = 0
		snd_jmp.play()
		velocity.y = JUMP_VELOCITY
	elif Input.is_joy_button_pressed(player_id,JOY_BUTTON_B) && double_jump == 1:
		double_jump +=1
		snd_jmp.play()
		velocity.y = JUMP_VELOCITY

	if !Input.is_joy_button_pressed(player_id,JOY_BUTTON_B) && double_jump == 0:
		double_jump +=1
		
	if Input.is_joy_button_pressed(player_id,JOY_BUTTON_DPAD_LEFT):
		direction = -1
	elif Input.is_joy_button_pressed(player_id,JOY_BUTTON_DPAD_RIGHT):
		direction = 1

func play_animations():
	if velocity.x != 0:
		sprite.play("run")
	else:
		sprite.play("default")
	
	if velocity.x < 0:
		sprite.flip_h = true
	else:
		sprite.flip_h = false
