extends Control


var games := {}
var selected_game := ""
var profiles := {}
var selected_profile := ""
func _ready():
	%Games.visible=false
	%GameTab.visible=false
	%Profiles.visible=false
	
	register_games()
	
	%Games.item_activated.connect(on_item_activated.bind("games"))
	%Profiles.item_activated.connect(on_item_activated.bind("profiles"))
	%ProfileAdd.pressed.connect(_add_new_profile)
	%ProfileLaunch.pressed.connect(_launch_profile)
	
	if games.size()==1:
		select_game(games.keys()[0])
		%GameClose.visible=false
	elif games.size()>1:
		load_games()
		%GameClose.pressed.connect(_return_to_list)
	else:
		PathHelper.create_game_folder("DummyGame")
		PathHelper.create_profile_folder("DummyGame","BaseProfile")
	
	
	lua.bind_libraries(["base", "coroutine", "debug", "table", "string", "math", "io", "os", "utf8", "package"])
	lua.push_variant("create_process", LuaFuncs._create_process)
	lua.push_variant("download_file", LuaFuncs.download_file)
	lua.push_variant("message", "Hello lua!")

func register_games():
	for gm in DirAccess.get_directories_at(PathHelper.data_path):
		var cfg := PathHelper.get_game_config(gm)
		var dt = {
			"name":cfg.get_value("Data","game_name","Dummy"),
			"image":cfg.get_value("Data","game_icon_path","icon.svg")
		}
		games[gm]=dt
	print("Registered games")

func select_game(key:String):
	print("selecting game under key: "+key)
	var game_data=games[key]
	
	var game_name :String= game_data.get("name") if game_data.has("name") else "UNKNOWN"
	var game_image :Texture= load(game_data.get("image")) if game_data.has("name") else load("res://icon.svg")
	
	selected_game=key
	
	await load_profiles()
	
	display_profiles()
	
	%GameName.text=game_name
	%GameIcon.texture=game_image
	
	%Games.visible=false
	%GameTab.visible=true
	%Profiles.visible=true

func load_games():
	print("Loading games list...")
	var list :ItemList=%Games
	list.clear()
	var i:=0
	for key in games.keys():
		var dt = games[key]
		var game_name :String= dt.get("name") if dt.has("name") else "UNKNOWN"
		var game_image :Texture= load(dt.get("image")) if dt.has("name") else load("res://icon.svg")
		list.add_item(game_name,game_image)
		list.set_item_metadata(i,key)
		i+=1
	%Games.visible=true


func load_profiles():
	for pf in DirAccess.get_directories_at(PathHelper.data_path):
		var cfg := PathHelper.get_profile_config(selected_game,pf)
		var dt = {
			"name":cfg.get_value("Data","profile_name","Dummy"),
			"image":cfg.get_value("Data","profile_icon_path","icon.svg")
		}
		profiles[pf]=dt
	print("Registered games")

func select_profile(key:String):
	var profile_data=profiles[key]
	
	var profile_name :String= profile_data.get("name") if profile_data.has("name") else "UNKNOWN"
	var profile_image :Texture= load(profile_data.get("image")) if profile_data.has("image") else load("res://icon.svg")
	var profile_desc :String= load(profile_data.get("desc")) if profile_data.has("desc") else "No description defined..."
	
	selected_profile=key
	
	%ProfileName.text=profile_name
	%ProfileIcon.texture=profile_image
	%ProfileDesc.text=profile_desc
	
	if !%ProfilePanel.visible:
		$Anim.play("switch_profile_view")

func display_profiles():
	print("Loading profiles list...")
	var list :ItemList=%Profiles
	list.clear()
	var i:=0
	for key in profiles.keys():
		var dt = profiles[key]
		var profile_name :String= dt.get("name") if dt.has("name") else "UNKNOWN"
		var profile_image :Texture= load(dt.get("image")) if dt.has("name") else load("res://icon.svg")
		list.add_item(profile_name,profile_image)
		list.set_item_metadata(i,key)
		i+=1

func on_item_activated(id:int,type:String):
	if type=="games":
		var key :String=%Games.get_item_metadata(id)
		select_game(key)
	elif type=="profiles":
		var key :String=%Profiles.get_item_metadata(id)
		select_profile(key)

func _return_to_list():
	selected_game=""
	selected_profile=""
	load_games()
	%Games.visible=true
	%GameTab.visible=false
	%Profiles.visible=false
	if %ProfilePanel.visible:
		$Anim.play_backwards("switch_profile_view")

func _add_new_profile():
	pass

var lua: LuaAPI = LuaAPI.new()
func _launch_profile():
	# Most methods return a LuaError in case of an error
	var err: LuaError = lua.do_file(PathHelper.data_path+PathHelper.game+"/game.lua")
	if err is LuaError:
		print("ERROR %d: %s" % [err.type, err.message])
		return
	
	var ret = lua.call_function("launch_profile", [
		PathHelper.data_path+PathHelper.game+"/",
		PathHelper.data_path+PathHelper.game+"/profiles/"+selected_profile+"/"
		])
	if ret is LuaError:
		print("ERROR %d: %s" % [ret.type, ret.message])
		return
