extends HTTPRequest

const Response = preload("res://scenes/util/Response.gd")

var callable : Callable
var auth_token: String
var base_address: String


# Called when the node enters the scene tree for the first time.
func _ready():
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta):
	pass


func post_http_request(url: String, request_data: String) -> Response:
	return await _send_http_request_sync(url, HTTPClient.METHOD_POST, request_data)

func patch_http_request(url: String, request_data: String) -> Response:
	return await _send_http_request_sync(url, HTTPClient.METHOD_PATCH, request_data)

func get_http_request(url: String, callback : Callable) -> bool:
	return _send_http_request(url, HTTPClient.METHOD_GET, callback)

func get_http_request_sync(url: String) -> Response:
	return await _send_http_request_sync(url, HTTPClient.METHOD_GET)

func _send_http_request_sync(url: String, method: HTTPClient.Method, request_data: String = "") -> Response:
	var result: Response = Response.new()
	result.status = FAILED
	result.code = HTTPClient.ResponseCode.RESPONSE_BAD_REQUEST
	result.data = {}
	
	var lambda = func(response):
		result.status = response.status
		result.code = response.code
		result.data = response.data

	print_debug("%s - %s - %s" % [url, method, request_data])

	if !_send_http_request(url, method, lambda, request_data):
		print_debug("early exit")
		return result
	
	await request_completed
	return result

func _send_http_request(url: String, method: HTTPClient.Method, callback : Callable, request_data : String = "") -> bool:
	callable = callback
	
	if url[0] != '/':
		url = "/" + url
	
	var _url = "{address}{url}".format({"address": base_address, "url": url})
	
	print_debug("%s request on %s with: %s" % [method, _url, request_data])
	
	var headers = ["X-AUTH-TOKEN: %s" % auth_token, "accept: application/json"]
	if method == HTTPClient.METHOD_PATCH:
		headers.append("Content-Type: application/merge-patch+json")
	elif method == HTTPClient.METHOD_POST:
		headers.append("Content-Type: application/json")
	
	var error = request(_url, headers, method, request_data)
	print_debug("%s" % error)
	return error == OK

func _on_request_completed(result, response_code, _headers, body):
	var response : Response = Response.new()
	response.status = FAILED
	response.code = response_code
	response.data = {}

	## Where to get the response to?
	if result == HTTPRequest.RESULT_SUCCESS and response_code / 100 == 2:
		response.status = OK
		var json = JSON.new()
		json.parse(body.get_string_from_utf8())
		response.data = json.get_data()
	else:
		print_debug("%s: %s" % [result, response_code])

	callable.call(response)
