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

#enum _DIRECTIONS {UP, DOWN, LEFT, RIGHT, NONE}
enum STATES {IDLE, ROLLING}

var state = STATES.IDLE
var current_direction
var stored_push_direction




func _ready() -> void:
	super._ready()
	stored_push_direction = DIRECTIONS.NONE
	self.pushed.connect(Callable(self, "set_roll_direction"))
	current_direction = DIRECTIONS.NONE
	
func _physics_process(delta: float) -> void:
	_handle_rolling()
	_handle_movement(delta)
	


func _handle_rolling():
	
	#it is a bit weird but it works, first store the push direction... (I tried a simple approach before but that did not work as expected)
	if requested_direction != DIRECTIONS.NONE and ray_front.is_colliding() and is_grid_aligned():
		var frontObject = ray_front.get_collider()
		
		if frontObject.is_in_group("breakable") and frontObject.has_method("hit"):
			frontObject.hit()
			hit()
		
		if requested_direction != DIRECTIONS.NONE:
				print ("okkkkkk")
				stored_push_direction = requested_direction
		
		requested_direction = DIRECTIONS.NONE
		current_direction = DIRECTIONS.NONE
	#and then push based on the stored push direction
	elif requested_direction == DIRECTIONS.NONE and stored_push_direction != DIRECTIONS.NONE and ray_front.is_colliding() and is_grid_aligned():
		var frontObject = ray_front.get_collider()
			
		if frontObject.is_in_group("pushable") and not frontObject.is_in_group("heavy"):
			push(frontObject, stored_push_direction)
		elif frontObject.get_parent().is_in_group("pushable") and not frontObject.is_in_group("heavy"):
			push(frontObject.get_parent(), stored_push_direction)
			
		stored_push_direction = DIRECTIONS.NONE
		
			
	else:
		requested_direction = current_direction
		



func hit():
	if is_grid_aligned():
		call_deferred("queue_free")

func set_roll_direction(direction):
	#push_enabled = false
	#push_timer.start()
	print ("rolling")
	if direction != DIRECTIONS.NONE:
		current_direction = direction
		print (direction)
	
func _on_Health_no_health() -> void:
	hit()





	
