extends "res://entities/GridBasedMovable.gd"

enum STATES {IDLE, MOVE}
#enum START_DIRS {UP, DOWN, LEFT, RIGHT}

enum _DIRECTIONS {UP, DOWN, LEFT, RIGHT, NONE}

var state = STATES.MOVE
var turned = false
var loop_count_hack = 0


var idle_started = false

@export var min_idle_time = 0.2
@export var max_idle_time = 0.2
#@export var start_direction: START_DIRS = START_DIRS.UP

@onready var current_direction = DIRECTIONS.NONE
@onready var idle_timer = $IdleTimer




func _ready() -> void:
	super._ready()
	requested_direction = randi_range(0, 3)
	update_rotation_point(requested_direction)
	

func _physics_process(delta: float) -> void:
	move()
	_handle_movement(delta)

func reset_to_idle():
	idle_timer.wait_time = randf_range(min_idle_time, max_idle_time)
	state = STATES.IDLE
	idle_started = true
	idle_timer.start()
	
func move():
	

	if state == STATES.IDLE:
		if idle_timer.get_time_left() < 0.1 and turned == false:
			var rand_dir = randi_range(0, 3)
			var can_move_to_ = can_move_to(rand_dir)
			loop_count_hack = 0

			while can_move_to_ == false:
				rand_dir = randi_range(0, 3)
				can_move_to_ = can_move_to(rand_dir)
				loop_count_hack += 1
				if loop_count_hack >= 999:
					break
			
		
			requested_direction = rand_dir
			update_rotation_point(requested_direction)
			turned = true
			
				
	if state == STATES.MOVE:
		if loop_count_hack >= 999:
				#print ("reset to idle after breaking out of an infinite loop")
				#print (str(name) + " was in an infinite loop...")
				reset_to_idle()

		if ray_front.is_colliding() and is_grid_aligned():
			
			if idle_timer.get_time_left() == 0 and idle_started == false:
				reset_to_idle()
			else:

				idle_started = false
		
		else:
			requested_direction = current_direction
			idle_started = false


	if ray_ground.is_colliding():
		var groundObject = ray_ground.get_collider()
		if groundObject != null and groundObject.is_in_group("player"):
			groundObject.hit()
			
	var frontObject = ray_front.get_collider()
	if frontObject != null and frontObject.is_in_group("player"):
		frontObject.hit()
	elif frontObject != null and frontObject.get_parent().is_in_group("player"):
		frontObject.get_parent().hit()
		
	if requested_direction == _DIRECTIONS.NONE:
		requested_direction = mesh_direction
	
func update_direction():
	if state == STATES.IDLE:
		
		update_rotation_point(requested_direction)
		
		current_direction = requested_direction
	
	state = STATES.MOVE

	
		
		
	
	




func _on_IdleTimer_timeout() -> void:

	update_direction()
	
	
	turned = false

func hit():
	call_deferred("queue_free")
