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: [
			load("res://src/GameWorld/Levels/Area1/Area11.tscn")
		],
		2: [

		],
		3: [

		]
	}
}

var _levels = [
	[_level_resources.pre_game, _level_resources.zones[1][0]],
]


export var _current_zone_level: = Vector2(0,0)

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



func _ready() -> void:
	var _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)):
	print("Changing level [%s] -> [%s]" % [oldLevel, newLevel])
	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].init_level_config(oldLevel, newLevel)
	_levels[newLevel.x][newLevel.y].set_player(_player)
	_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, _get_player_entering(oldLevel, newLevel))
	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(is_exit:bool, to_coords:Vector2):
	print("current level: %s, is_exit: %s to_coords: %s" % [_current_zone_level, is_exit, to_coords])
	_change_level(to_coords, _current_zone_level)
	yield(self, "level_ready")

