@tool
extends Node
class_name WeatherAPINode

signal received_current(json)
signal received_forecast(json)

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

@export var base_url: String = "http://api.weatherapi.com/v1/":
	set = 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)

func get_current(include_air_quality: bool = false):
	var url = _form_url('current.json', {'aqi': 'yes' if include_air_quality else 'no'})
	print(url)
	var out = await _wait_on_request(url)
	if out[0]:
		current_history.append(out)
		var parsed = JSON.parse_string(out[-1])
		received_current.emit(parsed)
		return parsed
	else:
		print("no answer")
		return out[1]

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

func get_forecast(days: int = 1, include_air_quality: bool = false, alerts: bool = false):
	var url = _form_url('current.json', {'aqi': _bool2YN(include_air_quality), 'days': days, 'alerts': _bool2YN(alerts)})
	var out = await _wait_on_request(url)
	if out[0]:
		var parsed = JSON.parse_string(out[-1])
		current_history.append(parsed)
		forecast_history.append(parsed)
		received_forecast.emit(parsed)
		received_current.emit(parsed)
		return parsed
	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 result = await http.request_completed
		result.append(result[-1].get_string_from_utf8())
		return [true] + result
	return [false, err]

func _form_url(endpoint: String = 'current.json', args: Dictionary = {}):
	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
