class_name MovingEnemyBehavior
extends BaseEnemyBehavior

var guard_path : GuardPath
@export var idle_timer = 2.0
var _idle_timer = 0.0
var current_idle_point : Node2D

var extended_anchor_state : Dictionary = {}
	
func _on_return_state_entered() -> void:
	in_moving_state = true
	enemy_nodes.navigation_agent.target_desired_distance = 3
	enemy_nodes.navigation_agent.target_position = guard_path.to_global(guard_path.curve.get_closest_point(guard_path.to_local(character_body.global_position)))
	$EnemyNodes/DynamicReturnTimer.start()
	
func _on_idle_state_processing(_delta: float) -> void:
	if Globals.paused:
		return
	if _idle_timer > 0 and current_idle_point:
		in_moving_state = false
		character_body.movement_velocity = Vector2(0,0)
		character_body.current_direction = Vector2(cos(current_idle_point.rotation), sin(current_idle_point.rotation))
	elif current_idle_point and current_idle_point != guard_path.get_next_watchpoint(global_position):
		_idle_timer = idle_timer
	else:
		in_moving_state = true
		if abs(global_position.distance_to(guard_path.pathfollow.global_position)) <= 10:
			guard_path.pathfollow.progress += 10
		var nav_point_direction = global_position.direction_to(guard_path.pathfollow.global_position)
		character_body.walk(nav_point_direction)

func _on_idle_state_entered() -> void:
	in_moving_state = true
	current_idle_point = guard_path.get_next_watchpoint(global_position)
	var offset = guard_path.curve.get_closest_offset(guard_path.to_local(global_position))
	guard_path.pathfollow.progress = offset + 10

func _on_dynamic_return_timer_timeout() -> void:
	enemy_nodes.navigation_agent.target_position = guard_path.to_global(guard_path.curve.get_closest_point(guard_path.to_local(character_body.global_position)))

func _on_return_state_exited() -> void:
	$EnemyNodes/DynamicReturnTimer.stop()

func decrement_timers(delta : float):
	super.decrement_timers(delta)
	if _idle_timer > 0:
		_idle_timer-= delta
		if _idle_timer <= 0:
			current_idle_point = guard_path.get_next_watchpoint(global_position)
	
func save_state():
	super.save_state()
	extended_anchor_state = {
		"current_offset" = guard_path.pathfollow.progress,
		"_idle_timer" = _idle_timer,
		"current_idle_point" = current_idle_point
	}

func reload_state():
	super.reload_state()
	guard_path.pathfollow.progress = extended_anchor_state.get("current_offset", guard_path.pathfollow.progress)
	_idle_timer = extended_anchor_state.get("_idle_timer", _idle_timer)
	current_idle_point = extended_anchor_state.get("current_idle_point", current_idle_point)
