extends Node2D

signal level_ready

var _level_resources := {

	"pre_game": load("res://src/GameWorld/Levels/PreGame.tscn"),
	"hub" : load("res://src/GameWorld/Levels/WorldHub.tscn"),
	"zones": {
		1: [

		],
		2: [

		],
		3: [

		]
	}
}

var _levels = [
	[_level_resources.pre_game, _level_resources.hub],
	[load("res://src/GameWorld/Levels/FirstLevels/TMP.tscn")],
	[load("res://src/GameWorld/Levels/FirstLevels/TMP2.tscn")]
]


export var _current_zone_level: = Vector2(0,1)

onready var _player:Player = (load("res://src/Actors/Player.tscn")).instance()



func _ready() -> void:
	_player.connect("died", self, "_on_player_died")
	_change_level(_current_zone_level)
	yield(self, "level_ready")
		
	

func _change_level( newLevel:Vector2 = Vector2.ZERO, oldLevel:Vector2 = Vector2(0,-1)):
	if oldLevel.y != -1:
		GameState.set_state(GameState.States.TRANSITIONING)
		Stage.fade_out(.5)
		yield(Stage, "fade_finished")
		_levels[oldLevel.x][oldLevel.y].remove_player()
		_levels[oldLevel.x][oldLevel.y].disconnect("level_exited", self, "_on_level_exited")
		$Level.remove_child(_levels[oldLevel.x][oldLevel.y])
	if !_levels[newLevel.x][newLevel.y].is_class("Node2D"):
		_levels[newLevel.x][newLevel.y] = _levels[newLevel.x][newLevel.y].instance()
	
	_levels[newLevel.x][newLevel.y].set_player(_player, _get_player_entering(oldLevel, newLevel))
	_levels[newLevel.x][newLevel.y].connect("level_exited", self, "_on_level_exited")
	$Level.add_child(_levels[newLevel.x][newLevel.y])
	_levels[newLevel.x][newLevel.y]._set_active(true)
	Stage.fade_in()
	yield(Stage, "fade_finished")
	GameState.set_state(_levels[newLevel.x][newLevel.y].game_state)
	_current_zone_level = newLevel
	emit_signal("level_ready")

func _get_player_entering(oldLevel:Vector2, newLevel:Vector2) -> bool:
	if oldLevel.y == -1: return true;
	return oldLevel.x < newLevel.x || (oldLevel.x == newLevel.x && oldLevel.y < newLevel.y)

func _on_player_died():
	var prev_state = _levels[_current_zone_level.x][_current_zone_level.y].game_state
	GameState.set_state(GameState.States.TRANSITIONING)
	Stage.fade_out(.8)
	yield(Stage, "fade_finished")
	Stage.fade_in(.8)
	yield(Stage, "fade_finished")
	GameState.set_state(prev_state)

func _on_level_exited(next_level:bool = true, zone:int = -1):
	print("current level: %s, next_level: %s zone: %s" % [_current_zone_level, next_level, zone])
	var next = Vector2.ZERO
	if zone != -1:
		next = Vector2(
			zone,
			0 if next_level else len(_levels[zone]) -1 
		)
	else:
		next = Vector2(
			_current_zone_level.x,
			_current_zone_level.y + 1 if next_level else _current_zone_level.y - 1 
		)
		if next.y < 0:
			next.x -= 1
			next.y = len(_levels[next.x]) - 1
		if next.y > len(_levels[next.x]) - 1:
			next.x += 1
			next.y = 0
			
		
	_change_level(next, _current_zone_level)
	yield(self, "level_ready")

