extends KinematicBody2D

const GRAVITY = 6000.0
const FLOOR_DETECT_DISTANCE = 30.0
const FLOOR_NORMAL = Vector2.UP

var _velocity = Vector2.ZERO
var speed = Vector2(400.0, 2000.0)
var anim = "idle"
var on_air = false
var health = 1
var floor_velocity = Vector2.ZERO

onready var landing_effect_scene = load("res://scenes/effects/landing_effect.tscn")

func _physics_process(delta):
	var dir = Vector2.ZERO
	var new_anim = "idle"
	
	var move_left = Input.is_action_pressed("move_left_key")
	var move_right = Input.is_action_pressed("move_right_key")
	var move_up = Input.is_action_just_pressed("jump_key")
	
	var is_jump_interrupted = Input.is_action_just_released("jump_key") and _velocity.y < 0.0
#	var is_on_floor = $floor_detector.is_colliding()
	var is_on_floor = is_on_floor()
	var snap_vector = Vector2.DOWN * FLOOR_DETECT_DISTANCE if dir.y == 0.0 else Vector2.ZERO
	
	if move_left:
		dir.x = -1
		new_anim = "run"
	elif move_right:
		dir.x = 1
		new_anim = "run"
		
	if move_up and is_on_floor:
		dir.y = -1
		
		Audio.play_sound("jump", false)
	else:
		dir.y = 0.0
		
	if !is_on_floor:
		new_anim = "falling" if _velocity.y > 0 else "jumping"
		on_air = true
	else:
		floor_velocity = get_floor_velocity() 
		if on_air:
			on_air = false
			var landing_effect = landing_effect_scene.instance()
			landing_effect.global_position = $floor_detector.global_position
			get_parent().add_child(landing_effect)
			Audio.play_sound("landing", false)

	if dir.y != 0.0:
		_velocity.y = speed.y * dir.y
	if is_jump_interrupted:
		_velocity.y *= 0.5
	
	_velocity.y += GRAVITY * delta
	_velocity.x = speed.x * dir.x
	
	if on_air:
		_velocity.x += floor_velocity.x
	
	_velocity = move_and_slide_with_snap(_velocity, snap_vector, FLOOR_NORMAL, not is_on_floor, 4, 0.9, false)
	
	if dir.x != 0:
		$sprite.scale.x = 1 if dir.x > 0 else -1
		
	if new_anim != anim:
		$AnimationPlayer.play(new_anim)
		anim = new_anim
		
func death(effect):
	Global.save_time()
	set_physics_process(false)
	$CollisionShape2D.set_deferred("disabled", true)
	var death_anim = "death_by_" + effect
	$AnimationPlayer.play(death_anim)
	Audio.play_sound(effect, false)
	yield(get_tree().create_timer(2), "timeout")
	Global.level.restart_level()

func apply_damage(damage, death_effect):
	health -= damage
	if health <= 0:	
		death(death_effect)
		
func bound():
	_velocity.y = -1400.0
