/* Talking to weathersnail, through c8-base's curl runner */
#include <gio/gio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "http.h"
#include "weather.h"

bool ws_allow_http(void) {
	return g_getenv("C8_ACCOUNTS_ALLOW_HTTP") != NULL;
}

char *ws_json_escape(const char *text) {
	GString *out = g_string_new(NULL);
	for (const unsigned char *p = (const unsigned char *)text; *p; p++) {
		if (*p == '"' || *p == '\\') {
			g_string_append_printf(out, "\\%c", *p);
		} else if (*p < 0x20) {
			g_string_append_printf(out, "\\u%04x", *p);
		} else {
			g_string_append_c(out, (char)*p);
		}
	}
	return g_string_free(out, FALSE);
}

static void run(const char *method, const char *url, const char *body,
		const char *token, const char *dest, ws_http_fn fn, void *data) {
	c8_http(&(struct c8_http){ .method = method, .url = url, .body = body,
		.token = token, .dest = dest, .accept = "application/json",
		.agent = "c8-weather/0.1 (cont8nuum)",
		.allow_http = ws_allow_http() }, fn, data);
}

void ws_http(const char *method, const char *url, const char *body,
		const char *token, ws_http_fn fn, void *data) {
	run(method, url, body, token, NULL, fn, data);
}

void ws_download(const char *url, const char *dest, ws_http_fn fn,
		void *data) {
	run("GET", url, NULL, NULL, dest, fn, data);
}
