extends Node

# Server download!
# Use this to download files!

signal download_process(downloaded_size, file_size)
signal download_complete(file_size)
signal download_content(content)

var file_url = ""
var file_name = ""
var file_downloaded_size = 0.0
var file_size = 0.0

var http_client = null
var timer = null

var is_downloading = false


func download_site(url):
	if is_downloading: return
	
	http_client.queue_free()
	http_client = null
	http_client = HTTPRequest.new()
	add_child(http_client)
	
	http_client.connect("request_completed", self, "download_site_complete")
	http_client.request(url, [], true, HTTPClient.METHOD_GET)
	is_downloading = true


# warning-ignore:unused_argument
# warning-ignore:unused_argument
# warning-ignore:unused_argument
func download_site_complete(result, response_code, headers, body):
	is_downloading = false
	http_client.disconnect("request_completed", self, "download_site_complete")
	emit_signal("download_content", body.get_string_from_utf8())


func download(file = "file.gts", url = "http://example.com/10MB.zip"):
	if is_downloading: return
	
	self.file_name = file
	self.file_url = url
	
	http_client.download_file = file
	http_client.use_threads = true
	http_client.request(url, [], true, HTTPClient.METHOD_GET)
	
	timer = Timer.new()
	timer.connect("timeout", self, "timer_timeout")
	add_child(timer)
	timer.start()
	
	is_downloading = true


# warning-ignore:unused_argument
func timer_timeout():
	if not is_downloading: return
	if http_client.get_http_client_status() != HTTPClient.STATUS_BODY:
		download_complete()
		return
	
	file_downloaded_size = float(http_client.get_downloaded_bytes())
	file_size = float(http_client.get_body_size())
	
	emit_signal("download_process", file_downloaded_size, file_size)
	pass


func download_complete():
	remove_child(timer)
	timer.disconnect("timeout", self, "timer_timeout")
	timer = null
	is_downloading = false
	
	http_client.queue_free()
	http_client = null
	http_client = HTTPRequest.new()
	add_child(http_client)
	
	emit_signal("download_complete", file_size)
	file_size = 0
	file_downloaded_size = 0


func _ready():
	http_client = HTTPRequest.new()
	add_child(http_client)
