extends Node3D

class_name LevelManager

var map: Node3D
var starting_map = "level0101.tscn"

func _ready():
	Global.level_mgr = self
	
func init():
	MetSys.set_save_data()
	goto_map(MetSys.get_full_room_path(starting_map))
	MetSys.room_changed.connect(on_room_changed)

func goto_map(map_path: String):
	var prev_map_position := Vector2i.MAX
	if map:
		prev_map_position = MetSys.get_current_room_instance().get_base_coords()
		map.queue_free()
		map = null
	
	map = load(map_path).instantiate()
	add_child(map)
	MetSys.current_layer = MetSys.get_current_room_instance().get_layer()
	var level_size = MetSys.get_current_room_instance().get_size()
	SignalManager.level_size_change.emit(level_size)
	
	if prev_map_position != Vector2i.MAX:
		var player = Global.character_mgr.get_player()
		var pos_pre = player.pos()
		var pos_change_xz = Vector2(MetSys.get_current_room_instance().get_base_coords() - prev_map_position) * MetSys.settings.in_game_cell_size
		pos_pre.x -= pos_change_xz.x
		pos_pre.z -= pos_change_xz.y
		player.set_pos(pos_pre)

func on_room_changed(target_map: String):
	goto_map(MetSys.get_full_room_path(target_map))
