class_name Player
extends Actor

const FLOOR_DETECT_DISTANCE = 20.0

export(String) var action_suffix = ""
var bounce = false
var bounce_vec = Vector2(0,0)
onready var platform_detector = $PlatformDetector
onready var sprite = $Sprite
onready var animation_player = $AnimationPlayer

func _physics_process(_delta):
	var direction = get_direction()
	var is_jump_interrupted = (Input.is_action_just_released("jump" + action_suffix) and _velocity.y < 0.0) if !bounce else false
	_velocity = calculate_move_velocity(_velocity, direction, speed, is_jump_interrupted,_delta)

	if _velocity.y > 0.0:
		bounce = false

	if is_on_floor():
		if bounce_vec != Vector2(0,0) and !bounce:
			#print("OK")
			bounce_vec = Vector2(0,0)
		if Input.is_action_just_pressed("jump"):
			$jump.play()
	if is_on_ceiling():
		if bounce_vec != Vector2(0,0):
			bounce_vec = Vector2(bounce_vec.x,0)

	var snap_vector = Vector2.DOWN * FLOOR_DETECT_DISTANCE if direction.y == 0.0 and !bounce else Vector2.ZERO
	var is_on_platform = platform_detector.is_colliding()
	_velocity = move_and_slide_with_snap(
		_velocity, snap_vector, FLOOR_NORMAL, not is_on_platform, 4, 0.9, false
	)

	if direction.x != 0:
		sprite.scale.x = 1 if direction.x > 0 else -1
#
	var animation = get_new_animation()
	if animation != animation_player.current_animation:
		animation_player.play(animation)


func get_direction():
	return Vector2(
		Input.get_action_strength("move_right" + action_suffix) - Input.get_action_strength("move_left" + action_suffix),
		-1 if is_on_floor() and Input.is_action_just_pressed("jump" + action_suffix) else 0
	)


# This function calculates a new velocity whenever you need it.
# It allows you to interrupt jumps.
func calculate_move_velocity(
		linear_velocity,
		direction,
		speed,
		is_jump_interrupted,
		delta
	):
	var velocity
	if bounce_vec.x != 0:
		velocity = bounce_vec
		bounce_vec.y += gravity * delta
	else:
		velocity = linear_velocity
		velocity.x = speed.x * direction.x
		if direction.y != 0.0:
			velocity.y = speed.y * direction.y
		if is_jump_interrupted:
			velocity.y = 0.0
	return velocity

func get_new_animation():
	var animation_new = ""
	if is_on_floor():
		animation_new = "run" if abs(_velocity.x) > 0.1 else "idle"
	else:
		animation_new = "falling" if _velocity.y > 0 else "jumping"
	return animation_new

func bounce_off_glove(strength,angle):
	bounce = true
	var rangle = round(angle)
	bounce_vec = Vector2(0,0)
	if rangle == 90:
		_velocity = Vector2(0,-strength)
	elif rangle == 270:
		_velocity = Vector2(0,strength)
	else:
		sprite.scale.x = -1 if (angle >= 0 and angle <= 90) or angle > 270 else 1
		var ang_rad = deg2rad(angle)
		bounce_vec = Vector2(-cos(ang_rad),-sin(ang_rad))*strength
