extends Node
class_name WeatherAPINode
tool

signal received_current(json)
signal received_forecast(json)

export var api_key:String
export var location:String = "Amsterdam"

export var base_url := "http://api.weatherapi.com/v1/" setget set_base_url
var http = HTTPRequest.new()

var current_history := []
var forecast_history := []

func set_base_url(newurl:String):
	if not newurl.begins_with('http://') and not newurl.begins_with('https://'):
		newurl = 'http://'+newurl
	if !newurl.ends_with('/'):
		newurl += '/'
	base_url = newurl

func _ready():
	add_child(http)
	http.connect("request_completed", self, "_on_http_response")

func get_current(include_air_quality:=false):
	var url = _form_url('current.json', {'aqi': 'yes' if include_air_quality else 'no'})
	print(url)
	var out = yield(_wait_on_request(url), "completed")
	if out[0]:
		current_history.append(out)
		out = JSON.parse(out[-1]).result
		emit_signal("received_current",out)
		return out
	else:
		print("no answer")
		return out[1]

func _bool2YN(b:bool):
	return 'yes' if b else 'no'

func get_forecast(days:=1, include_air_quality:=false, alerts:=false):
	var url = _form_url('current.json', {'aqi': _bool2YN(include_air_quality), 'days':days, 'alerts':_bool2YN(alerts)})
	var out = yield(_wait_on_request(url), "completed")
	if out[0]:
		out = JSON.parse(out[-1]).result
		current_history.append(out)
		forecast_history.append(out)
		emit_signal("received_forecast",out)
		emit_signal("received_current",out)
		return out
	else:
		return out[1]

func _wait_on_request(url)->Array:
	# Returns:
	# when answered: [http was answered<bool>, result, response_code, headers, raw_body, utf8_body]
	# when not answered: [false, error]
	var err = http.request(url)
	if err == OK:
		var out = yield(http, "request_completed")
		out.append(out[-1].get_string_from_utf8()) 
		return [true] + out
	yield()
	return [false, err]

func _form_url(endpoint:='current.json', args:={}):
	if endpoint.ends_with('/'):
		endpoint = endpoint.substr(0,len(endpoint))
	var out = base_url + endpoint
	out += '?key='+api_key
	out += '&q='+location
	for key in args:
		out += '&{0}={1}'.format([key, args[key]])
	return out

func _on_http_response(result: int, response_code: int, headers: PoolStringArray, body: PoolByteArray):
	pass
