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


var activated = false
var activated_and_open = false
var blocked = false
var deactivated_position
var activated_position
var position_without_height



enum _DIRS {UP, DOWN, LEFT, RIGHT}

@export var move_direction: _DIRS = _DIRS.UP





func _ready() -> void:
	
	super._ready()
	position_without_height = position
	position_without_height.y = 0
	deactivated_position = position_without_height
	
	activated_position = position_without_height + direction_to_vector(move_direction) * step_size

func _physics_process(delta: float) -> void:
	position_without_height = position
	position_without_height.y = 0
	if blocked:
		print ("was blocked...")
		if activated:
			open()
		else:
			close()
	elif activated == true and position_without_height == deactivated_position:
		print ("time to call open() again ?")
		open()
	elif activated == false and position_without_height == activated_position:
		print ("time to call close() again ?")
		close()
		
		#open()
	_handle_movement(delta)
	



func open(on_start = false):
	
	activated = true

	if deactivated_position != position_without_height:
		print ("not on deactivated position while called open")
		return
	
	if on_start == false:
		try_move(move_direction)
	else:
		try_move(move_direction, true, true)

	
	
	
	
func close():
	activated = false
	if activated_position != position_without_height:
		print ("not on activated position while called close")
		return
	
	try_move(get_opposite_direction(move_direction))
	
	

	


func try_move(direction, force: bool = false, instant: bool = false):
	#var movement_ok = true
	blocked = false

	move_to(direction, false, instant)
	

	if ray_front.is_colliding() and is_grid_aligned():
		var frontObject = ray_front.get_collider()
		var local_movedir = direction_to_vector(direction)
		var next_target_pos = position + local_movedir * step_size
		if frontObject != null:
			var _distance = (next_target_pos - frontObject.position).length()
			
			if frontObject.is_in_group("pushable"):
				print ("push...")
				
				
				blocked = not push(frontObject, direction, force, instant)
				
				
					
			elif frontObject.get_parent().is_in_group("pushable"):
				blocked = not push(frontObject.get_parent(), direction, force, instant)
			else:
				#movement_ok = false
				blocked = true
	if not blocked:
		activated_and_open = !activated_and_open
	

