/*
 * File: assets_json.h
 * JSON reader and typed accessors for art and campaign data.
 * Implementation include; compiled only through assets.c.
 */

#ifndef ASSETS_JSON_H
#define ASSETS_JSON_H

static char *json_string(const char **p)
{
    const char *start;
    char *out;
    size_t length = 0;
    expect(p, '"');
    start = *p;
    while (**p && **p != '"') {
        if ((unsigned char)**p < 32) fail("control character in JSON string");
        if (**p == '\\') {
            ++*p;
            if (!**p) fail("unterminated JSON escape");
        }
        ++*p;
    }
    if (!**p) fail("unterminated JSON string");
    out = allocate((size_t)(*p - start) + 1);
    while (start < *p) {
        unsigned char c = (unsigned char)*start++;
        if (c == '\\') {
            c = (unsigned char)*start++;
            switch (c) {
            case '"': case '\\': case '/': break;
            case 'b': c = '\b'; break;
            case 'f': c = '\f'; break;
            case 'n': c = '\n'; break;
            case 'r': c = '\r'; break;
            case 't': c = '\t'; break;
            case 'u': {
                int i, code = 0;
                for (i = 0; i < 4; ++i) {
                    int digit;
                    if (start >= *p || (digit = hex_digit(*start++)) < 0)
                        fail("invalid JSON unicode escape");
                    code = code * 16 + digit;
                }
                if (!code || code > 127) fail("asset strings require ASCII");
                c = (unsigned char)code;
                break;
            }
            default: fail("invalid JSON escape");
            }
        }
        out[length++] = (char)c;
    }
    ++*p;
    return out;
}

static Node *json_value(const char **p, int depth)
{
    Node *n, **tail;
    if (depth > 32) fail("JSON nesting exceeds 32");
    whitespace(p);
    n = new_node(**p);
    if (**p == '{' || **p == '[') {
        char end = *(*p)++ == '{' ? '}' : ']';
        tail = &n->child;
        whitespace(p);
        while (**p != end) {
            char *key = NULL;
            Node *child;
            if (n->type == '{') {
                Node *prior;
                key = json_string(p);
                for (prior = n->child; prior; prior = prior->next)
                    if (!strcmp(prior->key, key)) fail("duplicate JSON key: %s", key);
                expect(p, ':');
            }
            child = json_value(p, depth + 1);
            child->key = key;
            *tail = child;
            tail = &child->next;
            whitespace(p);
            if (**p != ',') break;
            ++*p;
            whitespace(p);
            if (**p == end) fail("trailing JSON comma");
        }
        expect(p, end);
    } else if (**p == '"') {
        n->text = json_string(p);
    } else {
        const char *start = *p;
        while (**p && !strchr(",}] \t\r\n", **p)) ++*p;
        if (*p == start) fail("missing JSON value");
        n->text = slice(start, (size_t)(*p - start));
        if (strcmp(n->text, "null") && strcmp(n->text, "true") && strcmp(n->text, "false")) {
            char *end;
            errno = 0;
            (void)strtod(n->text, &end);
            if (*end || errno || !(n->text[0] == '-' || isdigit((unsigned char)n->text[0])))
                fail("invalid JSON number: %s", n->text);
            n->type = 'n';
        }
    }
    return n;
}

static Node *read_json(const char *name)
{
    char path[4096], *text;
    const char *p;
    size_t size;
    Node *n;
    path_join(path, root_dir, name);
    text = read_file(path, &size);
    if (strlen(text) != size) fail("%s: embedded NUL", path);
    p = text;
    n = json_value(&p, 0);
    whitespace(&p);
    if (*p) fail("%s: trailing JSON data", path);
    free(text);
    return n;
}

static Node *member(Node *n, const char *key)
{
    Node *child;
    if (!n || n->type != '{') fail("expected JSON object for %s", key);
    for (child = n->child; child; child = child->next)
        if (!strcmp(child->key, key)) return child;
    fail("missing JSON member %s", key);
}

static Node *element(Node *n, int index, int count)
{
    Node *child, *result = NULL;
    int i = 0;
    if (!n || n->type != '[') fail("expected JSON array");
    for (child = n->child; child; child = child->next, ++i)
        if (i == index) result = child;
    if (i != count || !result) fail("expected JSON array with %d items", count);
    return result;
}

static const char *string(Node *n)
{
    if (!n || n->type != '"') fail("expected JSON string");
    return n->text;
}

static uint8_t byte(Node *n)
{
    if (!n || n->type != 'n') fail("expected JSON integer byte");
    return (uint8_t)integer(n->text, 0, 255, "color");
}

static void rgb(Node *n, uint8_t out[3])
{
    const char *s = string(n);
    int i;
    if (strlen(s) != 7 || s[0] != '#') fail("expected #RRGGBB color");
    for (i = 0; i < 3; ++i) {
        int hi = hex_digit(s[1 + i * 2]), lo = hex_digit(s[2 + i * 2]);
        if (hi < 0 || lo < 0) fail("invalid RGB hex color");
        out[i] = (uint8_t)(hi * 16 + lo);
    }
}

#endif
