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

export var invincible := false
export var speed := 80
export var acceleration := 80
export var is_harmful := true

func _ready() -> void:
	$StompDetector.monitoring = !invincible


# TODO Only moves when on screen
func execute_movement(delta: float) -> void:
	velocity.y += _gravity * delta
	var player_direction := player_on_floor_direction()
	if(player_direction != 0):
		velocity.x = PhysicsFunc.two_step_euler(velocity.x, acceleration * player_direction,
		mass, delta)
		velocity.x =  clamp(velocity.x, -speed, speed)
	else:
		velocity.x = PhysicsFunc.two_step_euler(velocity.x, acceleration * -sign(velocity.x),
		mass, delta)
	velocity.y = move_and_slide(velocity, FLOOR_NORMAL).y
	

# TODO Detects player over gaps
func player_on_floor_direction() -> float:
	for raycast in $LedgeDetectorRays.get_children():
		if raycast.is_colliding():
			var collider = raycast.get_collider()
			if collider.is_in_group("player"):
				return sign(collider.position.x - self.position.x)
	return 0.0

func _on_StompDetector_body_entered(body: Node) -> void:
	if !body.is_in_group("player"):
		return
	var incoming_vel_vector: Vector2 = body.velocity.normalized()
	print(rad2deg(abs(incoming_vel_vector.angle_to(Vector2.DOWN.rotated(rotation)))))
	if abs(incoming_vel_vector.angle_to(Vector2.DOWN.rotated(rotation))) > deg2rad(95) \
		&& is_harmful:
		print("too shallow entry")
		body.die()
		return
	signal_manager.emit_signal("got_stomped")
	#get_node("EnemyBody").disabled = true
	if(killable):
		remove_from_group("harmful")
		die()
	else:
		switch_spikes()

func switch_spikes() -> void:
	is_harmful = !is_harmful
	if $Sprite.frame == 0:
		$Sprite.frame = 1
	else:
		$Sprite.frame = 0
	
	


func die() -> void:
	queue_free()


func _on_EnemySkin_area_entered(area: Area2D) -> void:
	pass


func _on_EnemySkin_body_entered(body: Node) -> void:
	if body.is_in_group("player") && is_harmful:
		body.die()
