extends KinematicBody2D

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

export var patrol = false
export var patrol_area = Vector2.ZERO
export var health = 1
export var shipo = false

var _velocity = Vector2.ZERO
var dir = Vector2.ZERO
var speed = Vector2(200.0, 2000.0)
var anim = "idle"

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

func _physics_process(delta):
	
	var _is_on_floor = is_on_floor()
	var _is_on_wall = is_on_wall()
	var new_anim = "run"
	var is_on_edge = $edge_detector.is_colliding()
	var snap_vector = Vector2.DOWN * FLOOR_DETECT_DISTANCE if dir.y == 0.0 else Vector2.ZERO

	if !is_on_edge or _is_on_wall:
		dir.x *= -1

	_velocity.y += GRAVITY * delta
	_velocity.x = speed.x * dir.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 apply_damage(damage):
	health -= damage
	if health <= 0:
		death()

func death():
	set_physics_process(false)
	$CollisionShape2D.set_deferred("disabled", true)
	$damage_area.set_deferred("monitoring", false)
	$AnimationPlayer.play("death")
	Audio.play_sound("tumbo_death", false)

func _on_area_body_entered(body):
	if shipo:
		body.apply_damage(1,"damage")
		return
	if position.y - body.position.y < 30:
		body.apply_damage(1,"damage")
	else:
		body.bound()
		death()
	
func _ready():
	dir.x = -1
	$damage_area.connect("body_entered", self, "_on_area_body_entered")
