extends Node
class_name Room

var room_to_tile = []: set = setup_path_grid

var path_grid = AStar3D.new()

var room_to_door = []

var place_id: int = 0

func _process(delta: float) -> void:
	for i in path_grid.get_point_ids():
		for j in path_grid.get_point_connections(i):
			var i_pos = path_grid.get_point_position(i)
			var j_pos = path_grid.get_point_position(j)
			if i > 0:
				DebugDraw3D.draw_line(i_pos, j_pos, Color(0.613, 0.613, 0.613, 1.0))

func save():
	var save_data = {
#Basics
		"id": self.get_instance_id(),
		"type": "Room",
		"scene_file_path": scene_file_path,
		"parent": get_parent().get_instance_id(),
#Connections
		"place_id": place_id,
#Data
	}
	return save_data

func init_room(new_dict):
#When a room is created, run through these steps

	setup_path_grid(new_dict)
	for i in new_dict.values():
		i.room = self

func setup_path_grid(new_array):
#Sets up the A* grid of tiles that are in this room.
#TODO: Better grid changing

	path_grid.clear()
	room_to_tile = new_array
	var room_to_tile_positions: Array
		
	for i in room_to_tile:
		var id = path_grid.get_available_point_id()
		var point_pos = Vector3(i.place_position)
		path_grid.add_point(id, point_pos)
		room_to_tile_positions.append(point_pos)

		for n in Tile.direction_vector_dict.values():
			var neighbor_pos = point_pos + Vector3(n)
			if room_to_tile_positions.has(neighbor_pos):
				var closest = path_grid.get_closest_point(neighbor_pos)
				if (neighbor_pos) == Vector3(path_grid.get_point_position(closest)):
					path_grid.connect_points(id, closest)

func get_room_path(start, end):
	for i in room_to_tile:
		if i.place_position == Vector3i(end):
			var start_point = path_grid.get_closest_point(Vector3(start))
			var end_point = path_grid.get_closest_point(Vector3(end))
			var path = path_grid.get_point_path(start_point, end_point)
			return path
	return false
