extends Node

class_name StateMachine

@export var initial_state: State

var current_state: State
var states: Dictionary[StringName, State] = {}
var is_initialized: bool = false
var _enabled: bool = true
var enable: bool:
	set(value):
		_enabled = value
		_set_enabled(value)
	get:
		return _enabled

func _ready() -> void:
	_initialize_states()
	_set_enabled(enable)

func _initialize_states() -> void:
	if is_initialized:
		return

	for state in get_children():
		if state is State:
			states[state.state_id] = state
			state.transitioned.connect(_on_state_transition)

	is_initialized = true

func _set_enabled(value: bool) -> void:
	_enabled = value

	if not _enabled:
		return

	_initialize_states()

	if initial_state and current_state == null:
		current_state = initial_state
		current_state.enter()

func physics_process(delta) -> void:
	if current_state and _enabled:
		current_state.physics_update(delta)

func _on_state_transition(state: State, new_state_id: StringName) -> void:
	if state != current_state:
		return

	var new_state = states.get(new_state_id)
	if not new_state:
		return

	if current_state:
		current_state.exit()
	
	current_state = new_state
	current_state.enter()
