#include <stdlib.h>
#include <string.h>
#ifdef __GLIBC__
#include <malloc.h>
#endif
#include <glib.h>
#include "json.h"

struct parser {
	const char *p;
	int depth;
};

static struct json *parse_value(struct parser *ps);
static size_t free_tree(struct json *json);

static void skip_space(struct parser *ps) {
	while (*ps->p == ' ' || *ps->p == '\t' || *ps->p == '\n' || *ps->p == '\r') {
		ps->p++;
	}
}

static int hex4(const char *p) {
	int v = 0;
	for (int i = 0; i < 4; i++) {
		int c = g_ascii_xdigit_value(p[i]);
		if (c < 0) {
			return -1;
		}
		v = v * 16 + c;
	}
	return v;
}

static char *parse_string(struct parser *ps) {
	if (*ps->p != '"') {
		return NULL;
	}
	ps->p++;
	/* Most strings have no escapes: copied as they are, at their size */
	const char *q = ps->p;
	while (*q && *q != '"' && *q != '\\') {
		q++;
	}
	if (*q == '"') {
		char *plain = g_strndup(ps->p, (gsize)(q - ps->p));
		ps->p = q + 1;
		return plain;
	}
	GString *out = g_string_new_len(ps->p, q - ps->p);
	ps->p = q;
	while (*ps->p && *ps->p != '"') {
		char c = *ps->p++;
		if (c != '\\') {
			g_string_append_c(out, c);
			continue;
		}
		c = *ps->p++;
		switch (c) {
		case 'b': g_string_append_c(out, '\b'); break;
		case 'f': g_string_append_c(out, '\f'); break;
		case 'n': g_string_append_c(out, '\n'); break;
		case 'r': g_string_append_c(out, '\r'); break;
		case 't': g_string_append_c(out, '\t'); break;
		case 'u': {
			int cp = hex4(ps->p);
			if (cp < 0) {
				g_string_free(out, TRUE);
				return NULL;
			}
			ps->p += 4;
			/* Surrogate pairs */
			if (cp >= 0xd800 && cp < 0xdc00 && ps->p[0] == '\\' && ps->p[1] == 'u') {
				int lo = hex4(ps->p + 2);
				if (lo >= 0xdc00 && lo < 0xe000) {
					cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00);
					ps->p += 6;
				}
			}
			g_string_append_unichar(out, cp);
			break;
		}
		case '\0':
			g_string_free(out, TRUE);
			return NULL;
		default:
			g_string_append_c(out, c);
			break;
		}
	}
	if (*ps->p != '"') {
		g_string_free(out, TRUE);
		return NULL;
	}
	ps->p++;
	return g_string_free(out, FALSE);
}

static struct json *parse_container(struct parser *ps, bool object) {
	struct json *json = g_new0(struct json, 1);
	json->type = object ? JSON_OBJECT : JSON_ARRAY;
	ps->p++;
	skip_space(ps);
	char close = object ? '}' : ']';
	struct json **tail = &json->child;
	if (*ps->p == close) {
		ps->p++;
		return json;
	}
	while (true) {
		char *key = NULL;
		skip_space(ps);
		if (object) {
			key = parse_string(ps);
			skip_space(ps);
			if (key == NULL || *ps->p != ':') {
				g_free(key);
				free_tree(json);
				return NULL;
			}
			ps->p++;
		}
		struct json *value = parse_value(ps);
		if (value == NULL) {
			g_free(key);
			free_tree(json);
			return NULL;
		}
		value->key = key;
		*tail = value;
		tail = &value->next;
		skip_space(ps);
		if (*ps->p == ',') {
			ps->p++;
		} else if (*ps->p == close) {
			ps->p++;
			return json;
		} else {
			free_tree(json);
			return NULL;
		}
	}
}

static struct json *parse_value(struct parser *ps) {
	skip_space(ps);
	if (++ps->depth > 64) {
		return NULL;
	}
	struct json *json = NULL;
	const char *p = ps->p;
	if (*p == '{' || *p == '[') {
		json = parse_container(ps, *p == '{');
	} else if (*p == '"') {
		char *s = parse_string(ps);
		if (s) {
			json = g_new0(struct json, 1);
			json->type = JSON_STRING;
			json->string = s;
		}
	} else if (strncmp(p, "true", 4) == 0 || strncmp(p, "false", 5) == 0) {
		json = g_new0(struct json, 1);
		json->type = JSON_BOOL;
		json->boolean = *p == 't';
		ps->p += json->boolean ? 4 : 5;
	} else if (strncmp(p, "null", 4) == 0) {
		json = g_new0(struct json, 1);
		ps->p += 4;
	} else {
		/* Whole numbers, which is most of them, without strtod */
		const char *d = p + (*p == '-');
		double whole = 0;
		while (*d >= '0' && *d <= '9' && d - p < 16) {
			whole = whole * 10 + (*d++ - '0');
		}
		char *end;
		double n;
		if (d > p + (*p == '-') && *d != '.' && *d != 'e' && *d != 'E' &&
				(*d < '0' || *d > '9')) {
			n = *p == '-' ? -whole : whole;
			end = (char *)d;
		} else {
			n = g_ascii_strtod(p, &end);
		}
		if (end != p) {
			json = g_new0(struct json, 1);
			json->type = JSON_NUMBER;
			json->number = n;
			ps->p = end;
		}
	}
	ps->depth--;
	return json;
}

struct json *json_parse(const char *text) {
	if (text == NULL) {
		return NULL;
	}
	struct parser ps = { .p = text };
	struct json *json = parse_value(&ps);
	skip_space(&ps);
	if (json && *ps.p != '\0') {
		json_free(json);
		return NULL;
	}
	return json;
}

static size_t free_tree(struct json *json) {
	size_t count = 0;
	while (json) {
		struct json *next = json->next;
		count += 1 + free_tree(json->child);
		g_free(json->key);
		g_free(json->string);
		g_free(json);
		json = next;
	}
	return count;
}

/* A big document's tree is many times its text, and what the caller kept
 * of it was allocated among the nodes: freed, their memory would stay the
 * program's for good (a tile provider held 45 MB that way). So after a
 * big one what's free is given back. glibc only: musl's malloc returns
 * freed pages by itself, and has no malloc_trim. */
#define TRIM_NODES 20000

void json_free(struct json *json) {
	size_t nodes = free_tree(json);
#ifdef __GLIBC__
	if (nodes >= TRIM_NODES) {
		malloc_trim(0);
	}
#else
	(void)nodes;
#endif
}

struct json *json_get(const struct json *object, const char *key) {
	if (object == NULL || object->type != JSON_OBJECT) {
		return NULL;
	}
	for (struct json *c = object->child; c; c = c->next) {
		if (strcmp(c->key, key) == 0) {
			return c;
		}
	}
	return NULL;
}

struct json *json_at(const struct json *array, int index) {
	if (array == NULL || (array->type != JSON_ARRAY && array->type != JSON_OBJECT)) {
		return NULL;
	}
	struct json *c = array->child;
	while (c && index-- > 0) {
		c = c->next;
	}
	return c;
}

int json_length(const struct json *array) {
	int n = 0;
	for (struct json *c = array ? array->child : NULL; c; c = c->next) {
		n++;
	}
	return n;
}

const char *json_str(const struct json *json, const char *fallback) {
	return json && json->type == JSON_STRING ? json->string : fallback;
}

double json_num(const struct json *json, double fallback) {
	if (json && json->type == JSON_NUMBER) {
		return json->number;
	}
	if (json && json->type == JSON_STRING) {
		char *end;
		double n = g_ascii_strtod(json->string, &end);
		return end != json->string ? n : fallback;
	}
	return fallback;
}

bool json_bool(const struct json *json) {
	return json && json->type == JSON_BOOL && json->boolean;
}

static void dump_string(GString *out, const char *s) {
	g_string_append_c(out, '"');
	for (const unsigned char *p = (const unsigned char *)s; *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);
		}
	}
	g_string_append_c(out, '"');
}

static void dump(GString *out, const struct json *j) {
	char num[G_ASCII_DTOSTR_BUF_SIZE];
	switch (j->type) {
	case JSON_NULL:
		g_string_append(out, "null");
		break;
	case JSON_BOOL:
		g_string_append(out, j->boolean ? "true" : "false");
		break;
	case JSON_NUMBER:
		g_string_append(out, g_ascii_dtostr(num, sizeof(num), j->number));
		break;
	case JSON_STRING:
		dump_string(out, j->string);
		break;
	case JSON_ARRAY:
	case JSON_OBJECT:
		g_string_append_c(out, j->type == JSON_ARRAY ? '[' : '{');
		for (struct json *c = j->child; c; c = c->next) {
			if (c != j->child) {
				g_string_append_c(out, ',');
			}
			if (j->type == JSON_OBJECT) {
				dump_string(out, c->key ? c->key : "");
				g_string_append_c(out, ':');
			}
			dump(out, c);
		}
		g_string_append_c(out, j->type == JSON_ARRAY ? ']' : '}');
		break;
	}
}

char *json_dump(const struct json *json) {
	GString *out = g_string_new(NULL);
	if (json) {
		dump(out, json);
	} else {
		g_string_append(out, "null");
	}
	return g_string_free(out, FALSE);
}
