extends Control

# Define variables
var newest_version # The newest version available online
var newest_version_data # The data about the newest version online
var local_version # The version installed on this computer
var os_name # The simplified name of the OS (linux, or windows)
var suffix # 

# Every _process tick
func _process(delta):
	# If the newest_version variable exists,
	if newest_version != null:
		# Get the local_version (By looking at the store.json file)
		local_version = Versions.get_version()
		
		# If the local version is not null,
		if local_version:
			# If the newest version available (online) is greater than the currently installed version,
			if newest_version > local_version :
				# Set the Play_button's text to "Update"
				$Panel/Play_button.text = "Update"
			# If not,
			else:
				# Set the Play_button text to "Play"
				$Panel/Play_button.text = "Play"
		# If the local version *is* null,
		else:
			# Set the Play_button to "Update"
			$Panel/Play_button.text = "Update"

# When everything is loaded,
func _ready():
	# Determine the os_name
	if OS.get_name() == "X11": # X11 is linuxy-based
		os_name = "linux"
	elif OS.get_name() == "Windows":
		os_name = "windows"
	
	# Determine what to put after the executable name (the suffix)
	if os_name == "windows":
		suffix = ".exe"
	else:
		suffix = ""

	# Attempt to get the newest available online version
	var versions_request = HTTPRequest.new() # Get a new HTTPRequest node
	add_child(versions_request) # Add the node as a child of this one (Main_menu)
	
	# Connect the request_completed signal to self (this script)'s _versions_request_completed function
	versions_request.connect("request_completed", self, "_versions_request_completed")
	# Send an HTTP request to the releases page of UltraFlare on code.retroedge.tech
	var error = versions_request.request("https://code.retroedge.tech/api/v1/repos/UltraFlare/UltraFlare/releases?draft=false&pre-release=true&limit=1")

# Define _versions_request_completed
#  Handles the signal sent by the HTTPRequest when the download completes.
func _versions_request_completed(result, response_code, headers, body):
	# Get the JSON data
	var data = JSON.parse(body.get_string_from_ascii()).result
	# Get the newest version
	newest_version = data[0].tag_name
	# Set the newest_version_data to the data received.
	newest_version_data = data[0]
	
	print("Got versions!")

# Define _download_request_completed
#  Handles the signal sent by the HTTPRequest when the download completes.
func _download_request_completed(result, response_code, headers, body):
	# Get a new File object for the executable
	var dl_file = File.new()
	# Open the dl_file using the following path,
	dl_file.open(OS.get_config_dir()+"/UltraFlare/current/UltraFlare-"+os_name+"-x86_64"+suffix, 7)
	# Store the downloaded body in the dl_file
	dl_file.store_buffer(body)
	# Close the file
	dl_file.close()
	
	# Set the local_version (The one installed on this computer) to the newest_version_data's tag_name
	local_version = newest_version_data.tag_name
	# Write the current_version to the store file
	Store.write_store("current_version", local_version)
	
	# IF the os is "linux" based, use chmod to change the file to executable
	if os_name == "linux":
		OS.execute("chmod", ["+x", OS.get_config_dir()+"/UltraFlare/current/UltraFlare-"+os_name+"-x86_64"])
	
	# Enable (Un-disable?) the Play_button
	$Panel/Play_button.disabled = false

# When the play button is pressed,
func _on_Play_button_pressed():
	# If local_version is null, or the newest version available online is greater than the version currently installed,
	#  Update the game
	if not local_version or newest_version > local_version:
		# Get a new HTTPRequest node
		var download = HTTPRequest.new()
		var url # Define a place to hold the url
		
		# Add the HTTPRequest node as a child of the current node (Main_menu)
		add_child(download)
		
		# Connect the request_completed signal to self (This script)'s _download_request_completed function
		download.connect("request_completed", self, "_download_request_completed")
		
		# For each asset in the newest release's assets,
		for asset in newest_version_data.assets:
			# If the asset name matches the current operating system,
			if asset.name == "UltraFlare-"+os_name+"-x86_64"+suffix:
				# Set the url to the download url for that asset
				url = asset.browser_download_url
				break # End the for loop
		
		# Send an HTTP request to the url
		var error = download.request(url)
		
		# If the request was *created* successfully (Not neccessarily saying the server responded positively),
		if error == OK:
			# Disable the Play_button (So it can't be clicked multiple times)
			$Panel/Play_button.disabled = true
		# If not,
		else:
			# Debug message!
			print("Failed to send HTTP request to server! Error: "+error)
		
	# If not,
	#  Play the game
	else:
		# Attempt to execute the UltraFlare executable
		var exit_code = OS.execute(OS.get_config_dir()+"/UltraFlare/current/UltraFlare-"+os_name+"-x86_64"+suffix, [], false)
		
		# If the exit_code is anything other than -1,
		if exit_code != -1:
			# Close the launcher, the game should have started
			get_tree().quit()
		# If not, print out a debug message with the exit code
		else:
			print("Running UltraFlare failed with code: "+exit_code)
