extends Player
const PhysicsFunc = preload("res://src/Utilities/Physic/PhysicsFunc.gd")

onready var orientation: RayCast2D = $Orientation 
onready var jump_timer: Timer

export var score := 100

var start_x = 0
var in_air = false

func _ready():
	jump_timer = Timer.new()
	jump_timer.connect("timeout", self, "jump")
	add_child(jump_timer)

# TODO adapt to groups
# TODO Engine error here(what does it WANT???)
func _on_StompDetector_body_entered(body: Node) -> void:
	if body.global_position.y > get_node("StompDetector").global_position.y:
		return
	get_node("EnemyBody").disabled = true
	die()

func execute_movement(delta: float) -> void:
	velocity.y += _gravity * delta
	if sign(velocity.x) != orientation.cast_to.x:
		velocity.x *= -1
	velocity = move_and_slide(velocity, FLOOR_NORMAL)
	if(is_on_floor()):
		velocity = Vector2(0,0)
	if ($Left_Wallcast.is_colliding() || $Right_Wallcast.is_colliding()) && is_on_floor():
		orientation.cast_to.x *= -1


func die() -> void:
	queue_free()
	GlobalState.score += score


func _on_EnemySkin_area_entered(area:Area2D) -> void:
	if area.is_in_group("harmful"):
		get_node("EnemyBody").disabled = true
		die()


func searching() -> Vector2:
	if(is_on_floor()):
		if(jump_timer.is_stopped()):
			jump_timer.start(rand_range(0.1,3.333))
		if(in_air):
			in_air = false
			print("Jump distance: ",global_position.x - start_x)
	else:
		if(!in_air):
			start_x = global_position.x
		in_air = true
	return velocity

func jump():
	var v: Vector2 = velocity_for_jump_distance()
	var jump_height = (pow(v.length(), 2) * pow(sin(deg2rad(65)),2))/(2*_gravity)
	print("Jump height: ", jump_height)
	$CeilingRayCast.cast_to = Vector2(1.5*24 * sign(orientation.cast_to.x), - jump_height)
	velocity = v

func velocity_for_jump_distance(distance: float = 3*24, angle: float = deg2rad(65)) -> Vector2:
	var abs_velocity = sqrt((distance * _gravity)/sin(2*angle))
	return Vector2(abs_velocity,0).rotated(-1*angle)
