extends CharacterBody2D


const SPEED = 450
const JUMPFORCE = -500
const GRAVITY = 20
const RUNSPEED = SPEED * 2
const WALLJUMPFORCE = JUMPFORCE * 0.75
var WALLJUMPSPEED = SPEED * 8

var direction = Enum.DIRECTION.RIGHT

var canDoubleJump = false
var hasPlayedFallStop = false
var jumpHeightModifier = 0
var wasOnWall = false
var lastWallDirection = Enum.DIRECTION.LEFT


func _ready():
	pass


func _physics_process(delta):
	if Input.is_action_pressed("DIRECTION_LEFT"):
		velocity.x = -SPEED
		direction = Enum.DIRECTION.LEFT
		$Sprite2D.flip_h = true
		if self.is_running():
			velocity.x = -RUNSPEED
	elif Input.is_action_pressed("DIRECTION_RIGHT"):
		velocity.x = SPEED
		direction = Enum.DIRECTION.RIGHT
		$Sprite2D.flip_h = false
		if self.is_running():
			velocity.x = RUNSPEED
			
	set_up_direction(Vector2.UP)
	
	if is_on_floor():
		if Input.is_action_pressed("DIRECTION_LEFT") or Input.is_action_pressed("DIRECTION_RIGHT"):
			if self.is_running():
				$Sprite2D.play("run")
			else:
				$Sprite2D.play("walk")
		else:
			$Sprite2D.play("idle")
	
	
	# jump and fall animation
	if not is_on_floor():
		$Sprite2D.play("jump")
		if has_node("CheckFallStop"):
			if velocity.y > -JUMPFORCE:
				$CheckFallLanding.set_enabled(true)
				$CheckFallStop.set_enabled(true)
				if $CheckFallLanding.is_colliding():
					$Sprite2D.play("fall_stop_landing")
				elif $CheckFallStop.is_colliding():
					$Sprite2D.play("fall_stop")
				else:
					$Sprite2D.play("fall")
			else:
				$CheckFallLanding.set_enabled(false)
				$CheckFallStop.set_enabled(true)
	
	
	# fall down
	velocity.y += GRAVITY
	
	
	# jump
	if Input.is_action_just_pressed("JUMP"):
		if is_on_floor():
			canDoubleJump = true
			velocity.y = JUMPFORCE
			jumpHeightModifier = JUMPFORCE
		elif not is_on_floor() and not is_on_wall() and not wasOnWall and canDoubleJump:
			canDoubleJump = false
			velocity.y = JUMPFORCE
	if Input.is_action_pressed("JUMP"):
		jumpHeightModifier += 10
		if jumpHeightModifier > 0:
			jumpHeightModifier = 0
	if Input.is_action_just_released("JUMP"):
		velocity.y -= jumpHeightModifier
	
	
	if is_on_wall() and not is_on_floor():
		velocity.y *= 0.8
		$Sprite2D.play("wall")
		wasOnWall = true
		lastWallDirection = direction
	
	if not is_on_wall() and wasOnWall:
		wasOnWall = false
		$WalljumpTimer.start()
	
	if canWallJump() and Input.is_action_just_pressed("JUMP"):
		$WalljumpTimer.stop()
		velocity.y = WALLJUMPFORCE
		if lastWallDirection == Enum.DIRECTION.LEFT:
			velocity.x = WALLJUMPSPEED
			$Sprite2D.flip_h = false
		elif lastWallDirection == Enum.DIRECTION.RIGHT:
			velocity.x = -WALLJUMPSPEED
			$Sprite2D.flip_h = true
	
	
	# stop
	velocity = velocity.lerp(Vector2(0, velocity.y), 0.7)
	
	move_and_slide()


func is_running():
	return Input.is_action_pressed("RUN") and is_on_floor()


func canWallJump():
	return (is_on_wall() and not is_on_floor()) or not $WalljumpTimer.is_stopped()


func check_flag():
	# $Sprite.play("dance anim")
	print("FLAG CHECKED")