extends CharacterBody2D

class_name Npc

const SPEED = 100
const MINIMUM_STATE_DURATION = 3

const STATES = ['panic', 'dead']
const QUEUE_FREE_DELAY = 10

var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var direction = 0
var rising_speed = 0
@onready var original_parent = get_parent()

func _ready():
	pick_new_direction()
	$fsm.set_states(STATES)

func panic_state(delta):
	if is_on_wall():
		direction *= -1

	var state_duration_in_seconds = ceili($fsm.state_duration)
	var should_update = (
		$fsm.state_duration >= MINIMUM_STATE_DURATION
		&& state_duration_in_seconds % 2 == (randi() %2)
		)

	if should_update:
		pick_new_direction()
		$fsm.state_duration = 0

	velocity.x = direction
	velocity.y += gravity * delta
	move_and_slide()

func on_enter_dead_state():
	$shape.queue_free()

func dead_state(_delta):
	velocity = Vector2(0, -rising_speed)
	move_and_slide()

	if $fsm.state_duration > QUEUE_FREE_DELAY:
		queue_free()

func die(level_speed):
	$fsm.set_next_state('dead')
	rising_speed = level_speed


func grabbed(by):
	$shape.disabled = true
	$fsm.set_physics_process(false)
	reparent(by)
	position.y = 0

func dropped():
	$shape.disabled = false
	$fsm.set_physics_process(true)
	reparent(original_parent)
	rotation = 0


func pick_new_direction():
	direction = [1,-1][randi_range(0,1)] * SPEED
