extends Node
class_name Game

signal dialogue_finished

onready var dialogue_box = $Interface/PlayerGUI/DialogueBox
onready var inventory_system = $InventorySystem
onready var player_lifebar = $Interface/PlayerGUI/PlayerLifebar
onready var lifebar_builder = $LifebarBuilder
onready var player_cam = $PlayerCam

export(String) var start_map_scene_path



var current_map
var player


func _ready() -> void:
	_init_map(start_map_scene_path)
	


func _init_map(map_scene):
	
	current_map = load(map_scene).instance()
	
	
	add_child(current_map)
	
	
	if get_tree().get_nodes_in_group("player_spawn").size() > 0:
		player = get_tree().get_nodes_in_group("player_spawn")[0].spawn()
		if player.get_node("RemoteTransform2D"):
			player.get_node("RemoteTransform2D").remote_path = player_cam.get_path()

	for enemy in get_tree().get_nodes_in_group("enemy"):
		enemy.initiate()
		
	for map_changer in get_tree().get_nodes_in_group("map_changer"):
		map_changer.connect("map_changed", self, "on_MapChanger_map_changed")
		
	
	inventory_system.initiate()
	player_lifebar.initiate()
	lifebar_builder.initiate()
	
	
		
	assert(dialogue_box)
	for action in get_tree().get_nodes_in_group("map_action"):
		(action as MapAction).initialize(self)
	
	print ("init_map done")
		
	

func clean_map():
	current_map.set_name("map_delete")
	player.set_name("deleted")
	player.remove_from_group("actor")
	player.remove_from_group("player")
	
	for enemy in get_tree().get_nodes_in_group("enemy"):
		enemy.set_name("deleted")
		enemy.remove_from_group("enemy")
		enemy.queue_free()
	for map_changer in get_tree().get_nodes_in_group("map_changer"):
		map_changer.set_name("deleted")
		map_changer.remove_from_group("map_changer")
	for player_spawner in get_tree().get_nodes_in_group("player_spawn"):
		player_spawner.set_name("deleted")
		player_spawner.remove_from_group("player_spawn")
	for item_slot in get_tree().get_nodes_in_group("ItemSlot"):
		item_slot.set_name("deleted")
		item_slot.remove_from_group("ItemSlot")


	
	
	


func play_dialogue(data):
	dialogue_box.start(data)
	yield(dialogue_box, "dialogue_ended")
	
func on_MapChanger_map_changed(new_map):
	player.store_health_in_PlayerData()
	print ("game: change map")
	clean_map()
	current_map.queue_free()
	
	call_deferred("_init_map", new_map)
	#_init_map(new_map)
	
	
