class_name MapRoom
extends Node2D

@onready var tile_map_layer : TileMapLayer = $TileMapLayer
@onready var fallback_spawn : Marker2D = $FallbackSpawn
@onready var camera_limits: CameraLimits = $CameraLimits
@onready var doors: Area2D = $Doors

signal handled_player_positioning
var is_player_positioning_handled : bool = false

func _ready() -> void:
	doors.body_shape_entered.connect(use_door)

func use_door(_body_rid: RID, body: Node2D, _body_shape_index: int, local_shape_index: int) -> void:
	if body.is_in_group("Player"):
		SceneChanger.change_room(local_shape_index)

func get_room_size() -> Vector2:
	var tile_space : Rect2i = tile_map_layer.get_used_rect()
	var tile_size : Vector2i = tile_map_layer.tile_set.tile_size;
	return Vector2(tile_space.size.x * tile_size.x, tile_space.size.y * tile_size.y)

func handle(player : Player, input_recorder : InputRecorder, door_id : int = -1):
	if player:
		if player.player_base:
			player.player_base.position = Vector2.ZERO
		_handle_positioning(player, door_id)
	else:
		push_warning("No player.")
	if input_recorder:
		_handle_positioning(input_recorder, door_id)
	else:
		push_warning("No input recorder.")

func _handle_positioning(target : Node2D, door_id : int = -1):
	if _is_door_id_valid(door_id):
		_set_to_door_spawn(target, door_id)
	else:
		_set_to_fallback_spawn(target)
	if target is Player:
		is_player_positioning_handled = true
		handled_player_positioning.emit()

func _set_to_fallback_spawn(target : Node2D):
	target.global_position = fallback_spawn.global_position

func _set_to_door_spawn(target : Node2D, door_id : int):
	target.global_position = doors.get_child(door_id).get_node("InDirection").global_position;

func _is_door_id_valid(door_id : int):
	return door_id >= 0 and door_id < doors.get_child_count()

func get_camera_limits() -> Vector4:
	return camera_limits.get_camera_limits()
