extends Node2D

signal back_title

var pack_file = preload("res://resources/prefabs/Pack.tscn")

var has_update = false
var go_update = false
var new_version = "0.0"

var backup_pack_content = ""

var menu_item = 0
var pack_count = 0

func activate():
	
	DLC.load_dlc()
	
	has_update = false
	go_update = false
	menu_item = 0
	pack_count = 0
	$PackContent.hide()
	$Buttons.hide()
	$Download.hide()
	$PacksInfo.show()
	$PackContent/Packs.position.y = 0
	for pack in $PackContent/Packs.get_tree().get_nodes_in_group("PackItem"):
		pack.disconnect("pack_download", self, "input_disconnect")
		pack.disconnect("pack_complete", self, "input_connect")
		$PackContent/Packs.remove_child(pack)
		pack.queue_free()
	$PacksInfo.text = "Verifying for new packs..."
	$UpdateInfo.text = "Verifying update, please wait..."
	$PackContent/VScrollBar.value = 0
	# warning-ignore:return_value_discarded
	Server.connect("download_content", self, "verify_update")
	Server.download_site("URL/version.php?version=" + Game.version)
	input_connect()
	
	
func verify_update(content):
	Server.disconnect("download_content", self, "verify_update")
	new_version = content
	var godotversion = float(str(Engine.get_version_info()['major']) + "." + str(Engine.get_version_info()['minor']))
	var version = float(content)
	if version > float(Game.version):
		if godotversion < 3.4:
			$UpdateInfo.text = "UPDATE IS AVALIABLE!\nNew version: v" + content + "\n\nUnfortunately, this update uses the\nlatest version of Godot Engine.\n\nPlease redownload the complete game at\nhttps://xptz.itch.io/giantessrun\n\nDon't worry, your progress is saved. =D"
			has_update = false
			go_update = false
		else:
			$UpdateInfo.text = "UPDATE IS AVALIABLE!\nNew version: v" + content + "\nDo you want to update now?"
			$Buttons.show()
			has_update = true
			go_update = true
	else:
		$UpdateInfo.text = "NO UPDATE AVALIABLE!\nActual version: v" + Game.version
		has_update = false
		go_update = false
	
	# warning-ignore:return_value_discarded
	Server.connect("download_content", self, "verify_packs")
	Server.download_site("URL/packs/index.php?v=2")


func verify_packs(content):
	if content == null: content = backup_pack_content
	else: backup_pack_content = content
	Server.disconnect("download_content", self, "verify_packs")
	var json_content = JSON.parse(content)
	var top = 0
	
	# If empty, it means the server returned error, nothing to show, nothing to do...
	if not content:
		$PacksInfo.text = "Error connecting to the server.\nPlease try again later.\n\nPress ESC to return."
		return
	
	# but if the server acted as expected, so it must go on.
	for pack_info in json_content.result:
		var pack = pack_file.instance()
		pack.change_text(pack_info['title'], pack_info['description'], pack_info['author'], pack_info['version'])
		pack.packname = pack_info['filename']
		pack.artwork = pack_info['artwork']
		pack.get_node("Selection").hide()
		pack.position.y = top
		pack.name = "Pack_" + str(pack_count + 1)
		pack.add_to_group("PackItem")
		top = top + 160
		pack.connect("pack_download", self, "input_disconnect")
		pack.connect("pack_complete", self, "input_connect")
		$PackContent/Packs.add_child(pack)
		pack_count = pack_count + 1
		pack.load_image()
	
	$PackContent/Packs/Selection.hide()
	$PackContent.show()
	$PacksInfo.hide()
	$PackContent/VScrollBar.page = (100 / pack_count - 1)
	
	if not go_update: on_down()


func exit():
	input_disconnect()
	emit_signal("back_title")


func input_connect():
	# warning-ignore:return_value_discarded
	Controller.connect("controller_up", self, "on_up")
	# warning-ignore:return_value_discarded
	Controller.connect("controller_down", self, "on_down")
	# warning-ignore:return_value_discarded
	Controller.connect("controller_enter", self, "on_enter")
	# warning-ignore:return_value_discarded
	Controller.connect("controller_jump", self, "on_enter")
	# warning-ignore:return_value_discarded
	Controller.connect("controller_escape", self, "exit")

func input_disconnect():
	# warning-ignore:return_value_discarded
	Controller.disconnect("controller_up", self, "on_up")
	# warning-ignore:return_value_discarded
	Controller.disconnect("controller_down", self, "on_down")
	# warning-ignore:return_value_discarded
	Controller.disconnect("controller_enter", self, "on_enter")
	# warning-ignore:return_value_discarded
	Controller.disconnect("controller_jump", self, "on_enter")
	# warning-ignore:return_value_discarded
	Controller.disconnect("controller_escape", self, "exit")


func on_up():
	for pack in $PackContent.get_tree().get_nodes_in_group("PackItem"):
		pack.get_node("Selection").hide()
	menu_item = menu_item - 1
	
	if menu_item < 0: menu_item = 0
	if menu_item < 1 and go_update:
		$Buttons/Selected.show()
		$PackContent/Packs/Selection.hide()
	elif menu_item < 1 and not go_update:
		menu_item = 1
		if $PackContent/Packs.get_node("Pack_" + str(menu_item)).installed:
			$PackContent/Packs.get_node("Pack_" + str(menu_item)).get_node("Selection").show()
	elif not $PackContent/Packs.get_node("Pack_" + str(menu_item)).installed:
		$PackContent/Packs.get_node("Pack_" + str(menu_item)).get_node("Selection").show()
	
	$PackContent/Packs/Selection.position.y = (menu_item - 1) * 160
	
	$PackContent/Packs.position.y = 450 - (menu_item * 160)
	if $PackContent/Packs.position.y > 0: $PackContent/Packs.position.y = 0
	
	if pack_count > 1:
		$PackContent/VScrollBar.value = (100 / pack_count - 1) * (menu_item - 1)
		$PackContent/VScrollBar.page = (100 / pack_count - 1)
	pass

func on_down():
	for pack in $PackContent/Packs.get_tree().get_nodes_in_group("PackItem"):
		pack.get_node("Selection").hide()
	menu_item = menu_item + 1
	if menu_item > pack_count: menu_item = pack_count
	$Buttons/Selected.hide()
	$PackContent/Packs/Selection.show()
	if menu_item > 0:
		if not $PackContent/Packs.get_node("Pack_" + str(menu_item)).installed:
			$PackContent/Packs.get_node("Pack_" + str(menu_item)).get_node("Selection").show()
		
	$PackContent/Packs/Selection.position.y = (menu_item - 1) * 160
	
	$PackContent/Packs.position.y = 450 - (menu_item * 160)
	if $PackContent/Packs.position.y > 0: $PackContent/Packs.position.y = 0
	
	if pack_count > 1:
		$PackContent/VScrollBar.value = (100 / pack_count - 1) * (menu_item - 1)
		$PackContent/VScrollBar.page = (100 / pack_count - 1)
	pass

func on_enter():
	
	if menu_item > 0: 
		if not $PackContent/Packs.get_node("Pack_" + str(menu_item)).installed:
			$PackContent/Packs.get_node("Pack_" + str(menu_item)).download_pack()
		return
	
	if not go_update: return
	input_disconnect()
	$Download.show()
	
	Server.connect("download_complete", self, "download_complete")
	Server.connect("download_process", self, "download_process")
	Server.download("GIANTESSRUN.pck", "URL/updates/update-v" + new_version + ".update")

# warning-ignore:unused_argument
func download_process(file_size, file_total):
	var total = int(file_size / 1024 / 1024)
	$Download/Downloaded.text = "Downloaded " + str(total) + "MB..."

# warning-ignore:unused_argument
func download_complete(file_size):
	$Download/Downloaded.text = "Download complete! Closing game..."
	Server.disconnect("download_complete", self, "download_complete")
	Server.disconnect("download_process", self, "download_process")
	Game.fade_close(1.5)



