extends Node

var currentversion = 00
var status = 0
var downloaded_bytes = 0
var body_size = 0
var dowload = true

export var versionfile = 'https://git.galodev.net/galo/ghosthandupdate/raw/master/version.json'
export var pckfile = 'https://download1645.mediafire.com/u9zz5bf2gvng/e8fuz27b4t5uvvq/GhostHand.pck'

func _ready():
	if ResourceLoader.exists('user://patches/currentversion.tres'):
		var loader = load("user://patches/currentversion.tres")
		currentversion = loader.data[0]['version']
		print(currentversion)
	var directory = Directory.new()
	if directory.dir_exists("user://patches"):
		pass
	else:
		directory.make_dir("user://patches")
	$HTTPRequest2.request(versionfile)

func dowloadupdate():
	print('dowloading patch')
	$HTTPRequest.set_download_file('res://GhostHand.pck')
	$HTTPRequest.request(pckfile)

func _on_HTTPRequest_request_completed(result, response_code, headers, body):
	if response_code == 200:
		set_process(false)
		$Label.text = 'your dowload just finished'
		$ProgressBar.value = 100
#		ProjectSettings.load_resource_pack('user://patches/newpatch.pck')
#		get_tree().change_scene_to(load("res://Login/Client.tscn"))
	else:
		server_connect_fail()

func server_connect_fail():
	$Label.text = 'server connection failure!'
	print('failed to connect to server')
#		if ResourceLoader.exists('user://patches/newpatch.pck'):
#			ProjectSettings.load_resource_pack('user://patches/newpatch.pck')
#		get_tree().change_scene_to(load("res://Login/Client.tscn"))

func _on_HTTPRequest2_request_completed(result, response_code, headers, body):
	if response_code == 200:
		var data = JSON.parse(body.get_string_from_ascii())
		var dataprocess = data.result
		print(body.get_string_from_ascii())
		print(dataprocess)
		body_size = dataprocess['size']
		var dict = Directory.new()
		if dataprocess['version'] > currentversion:
			dowloadupdate()
			dowload = false
			var data2 = load("res://dataresource.gd").new()
			data2.data = [dataprocess]
			ResourceSaver.save('user://patches/currentversion.tres', data2)
		else:
			print('no version to dowload')
			$Label.text = 'you are on the most recent version!!!'
#			ProjectSettings.load_resource_pack('user://patches/newpatch.pck')
#			get_tree().change_scene_to(load("res://Client/Client.tscn"))
	else:
		server_connect_fail()
		$Label.text = 'server connection failure!'
	pass # Replace with function body.

func force_update():
	dowloadupdate()
	dowload = false

func _process(delta):
	status = $HTTPRequest.get_http_client_status()
	downloaded_bytes = $HTTPRequest.get_downloaded_bytes()
	if not dowload:
		$Label.text = 'dowloading '+str(downloaded_bytes/1024) +' kbs of '+ str(int(body_size)/1024) +' kbs'
		$ProgressBar.value = downloaded_bytes*100/body_size
