extends Node3D

class_name LevelManager

var level: Node3D
var level_path : String
var load_time : float
var load_control_time : float

func _ready():
	Global.level_mgr = self
	
func init():
	MetSys.set_save_data()
	goto_level(MetSys.get_full_room_path(Setting.starting_level))
	MetSys.room_changed.connect(on_room_changed)

func _process(delta):
	if Global.is_level_loading:
		if load_time > 0:
			load_time -= delta
			return
		var status = ResourceLoader.load_threaded_get_status(level_path)
		match status:
			ResourceLoader.ThreadLoadStatus.THREAD_LOAD_IN_PROGRESS:return
			ResourceLoader.ThreadLoadStatus.THREAD_LOAD_LOADED:pass
			_:print("关卡加载错误");return
		goto_level_end()
		Global.is_level_loading_contorl = true
		load_control_time = Setting.level_loading_control_time
	elif Global.is_level_loading_contorl:
		if load_control_time > 0:
			load_control_time -= delta
			return
		Global.is_level_loading_contorl = false

func on_room_changed(target_level: String):
	goto_level(MetSys.get_full_room_path(target_level))
	
func goto_level(new_level_path: String):
	if Global.is_level_loading:
		print("连续进入关卡:",new_level_path)
		return
	print("goto_level:",new_level_path)
	level_path = new_level_path
	ResourceLoader.load_threaded_request(level_path)
	Global.is_level_loading = true
	if level:
		load_time = Setting.level_loading_min_time
		SignalManager.level_loading_start.emit()
	else:
		load_time = 0
		goto_level_end()
		
func goto_level_end():
	var prev_level_position := Vector2i.MAX
	if level:
		prev_level_position = MetSys.get_current_room_instance().get_base_coords()
		level.queue_free()
		level = null
		
	level = ResourceLoader.load_threaded_get(level_path).instantiate()
	add_child(level)
	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_level_position != Vector2i.MAX:
		var player = Global.character_mgr.get_player()
		var pos_pre = player.pos()
		var level_position_now = MetSys.get_current_room_instance().get_base_coords()
		var pos_change_xz = Vector2(level_position_now - prev_level_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)
	
	Global.is_level_loading = false
	Global.currlevel_name = level_path
	SignalManager.level_loading_end.emit()
