/*
 * File: assets_tmx.h
 * XML reader, TMX map loading and map-format validation.
 * Implementation include; compiled only through assets.c.
 */

#ifndef ASSETS_TMX_H
#define ASSETS_TMX_H

static char *xml_name(const char **p)
{
    const char *start = *p;
    while (isalnum((unsigned char)**p) || strchr("_:-.", **p) != NULL) {
        if (!**p) break;
        ++*p;
    }
    if (*p == start) fail("missing XML name");
    return slice(start, (size_t)(*p - start));
}

static char *xml_text(const char *start, size_t length)
{
    char *out = allocate(length + 1);
    size_t i = 0, used = 0;
    while (i < length) {
        if (start[i] == '&') {
            static const char *const names[] = {"&amp;", "&lt;", "&gt;", "&quot;", "&apos;"};
            static const char values[] = "&<>\"'";
            int j;
            for (j = 0; j < 5; ++j) {
                size_t len = strlen(names[j]);
                if (len <= length - i && !memcmp(start + i, names[j], len)) {
                    out[used++] = values[j];
                    i += len;
                    break;
                }
            }
            if (j == 5) fail("unsupported XML entity (use plain ASCII or named entities)");
        } else out[used++] = start[i++];
    }
    return out;
}

static void xml_misc(const char **p)
{
    for (;;) {
        const char *end;
        whitespace(p);
        if (!strncmp(*p, "<?", 2)) {
            end = strstr(*p + 2, "?>");
            if (!end) fail("unterminated XML declaration");
            *p = end + 2;
        } else if (!strncmp(*p, "<!--", 4)) {
            end = strstr(*p + 4, "-->");
            if (!end) fail("unterminated XML comment");
            *p = end + 3;
        } else break;
    }
}

static Node *xml_node(const char **p, int depth)
{
    Node *n = new_node('<'), **tail;
    if (depth > 32) fail("XML nesting exceeds 32");
    expect(p, '<');
    n->key = xml_name(p);
    tail = &n->attrs;
    whitespace(p);
    while (**p != '>' && **p != '/') {
        Node *a = new_node('='), *prior;
        const char *start;
        char quote;
        a->key = xml_name(p);
        for (prior = n->attrs; prior; prior = prior->next)
            if (!strcmp(prior->key, a->key)) fail("duplicate XML attribute %s", a->key);
        expect(p, '=');
        whitespace(p);
        quote = *(*p)++;
        if (quote != '\'' && quote != '"') fail("XML attributes must be quoted");
        start = *p;
        while (**p && **p != quote) ++*p;
        if (!**p) fail("unterminated XML attribute");
        a->text = xml_text(start, (size_t)(*p - start));
        ++*p;
        *tail = a;
        tail = &a->next;
        whitespace(p);
    }
    if (**p == '/') {
        ++*p;
        expect(p, '>');
        return n;
    }
    expect(p, '>');
    tail = &n->child;
    for (;;) {
        xml_misc(p);
        if (!strncmp(*p, "</", 2)) {
            char *closing;
            *p += 2;
            closing = xml_name(p);
            if (strcmp(closing, n->key)) fail("mismatched XML closing tag %s", closing);
            free(closing);
            expect(p, '>');
            return n;
        }
        if (**p == '<') {
            Node *child = xml_node(p, depth + 1);
            *tail = child;
            tail = &child->next;
        } else {
            const char *start = *p;
            while (**p && **p != '<') ++*p;
            if (!**p) fail("unterminated XML element %s", n->key);
            if (n->text) fail("mixed XML content is unsupported");
            n->text = xml_text(start, (size_t)(*p - start));
        }
    }
}

static const char *attr(Node *n, const char *name)
{
    Node *a;
    for (a = n->attrs; a; a = a->next)
        if (!strcmp(a->key, name)) return a->text;
    return "";
}

static void attr_is(Node *n, const char *name, const char *value)
{
    if (strcmp(attr(n, name), value)) fail("%s: %s must be %s", n->key, name, value);
}

static Node *child_named(Node *n, const char *tag, const char *name)
{
    Node *c, *found = NULL;
    for (c = n->child; c; c = c->next)
        if (!strcmp(c->key, tag) && (!name || !strcmp(attr(c, "name"), name))) {
            if (found) fail("duplicate %s %s", tag, name ? name : "");
            found = c;
        }
    if (!found) fail("missing %s %s", tag, name ? name : "");
    return found;
}

static int coordinate(Node *n, const char *name, int min, int max)
{
    const char *s = attr(n, name);
    char *end;
    double value;
    errno = 0;
    value = strtod(s, &end);
    if (!*s || *end || errno || !isfinite(value) || value < min || value > max
        || fmod(value, 16.0) != 0)
        fail("units: %s must be grid-aligned (%d..%d)", name, min, max);
    return (int)value / 16;
}

static void load_map(const char *path, Level *level)
{
    char *text, source[4096], expected[4096], canonical[4096], directory[4096];
    const char *p;
    size_t size;
    Node *map, *c, *layer, *data, *group, *tileset;
    int i, hq[2] = {0,0}, teams = 0, occupied[CELLS] = {0}, properties = 0;
    memset(level, 0, sizeof(*level));
    level->cash = 5;
    text = read_file(path, &size);
    if (strlen(text) != size) fail("%s: embedded NUL", path);
    p = text;
    xml_misc(&p);
    map = xml_node(&p, 0);
    xml_misc(&p);
    if (*p || strcmp(map->key, "map")) fail("%s: expected one TMX map", path);
    attr_is(map, "orientation", "orthogonal");
    attr_is(map, "width", "16"); attr_is(map, "height", "10");
    attr_is(map, "tilewidth", "16"); attr_is(map, "tileheight", "16");
    attr_is(map, "infinite", "0");
    for (c = map->child; c; c = c->next) {
        Node *property;
        if (strcmp(c->key, "properties")) continue;
        for (property = c->child; property; property = property->next) {
            const char *value;
            long funds;
            if (strcmp(property->key, "property") || strcmp(attr(property, "name"), "starting_funds"))
                continue;
            if (++properties > 1) fail("duplicate starting_funds");
            attr_is(property, "type", "int");
            value = attr(property, "value");
            if (!*value && property->text) value = property->text;
            funds = integer(value, 0, 99000, "starting_funds");
            if (funds % 1000) fail("starting_funds must be a multiple of 1000");
            level->cash = (int)(funds / 1000);
        }
    }
    tileset = child_named(map, "tileset", NULL);
    attr_is(tileset, "firstgid", "1");
    if (!full_path(directory, path)) fail("cannot resolve map path %s", path);
    for (i = (int)strlen(directory) - 1; i >= 0; --i)
        if (directory[i] == '/' || directory[i] == '\\') { directory[i] = 0; break; }
    p = attr(tileset, "source");
    if (*p == '/' || *p == '\\' || (strlen(p) > 1 && p[1] == ':')) {
        if (strlen(p) >= sizeof(source)) fail("tileset path too long");
        strcpy(source, p);
    } else path_join(source, directory, p);
    if (!full_path(canonical, source)) fail("cannot resolve tileset %s", source);
    path_join(source, root_dir, "assets/tiles.tsx");
    if (!full_path(expected, source) || path_compare(canonical, expected))
        fail("use the AtariWars assets/tiles.tsx tileset");
    layer = child_named(map, "layer", "terrain");
    attr_is(layer, "width", "16"); attr_is(layer, "height", "10");
    data = child_named(layer, "data", NULL);
    attr_is(data, "encoding", "csv");
    if (*attr(data, "compression")) fail("TMX terrain must use uncompressed CSV");
    p = data->text ? data->text : "";
    for (i = 0; i < CELLS; ++i) {
        char *end;
        long gid;
        whitespace(&p);
        errno = 0;
        gid = strtol(p, &end, 10);
        if (p == end || errno || !((gid >= 1 && gid <= 10) || gid == 23))
            fail("terrain: expected 160 GIDs 1..10 or 23");
        level->terrain[i] = (uint8_t)(gid == 23 ? 10 : gid - 1);
        if (gid == 8 || gid == 9) ++hq[gid - 8];
        p = end;
        whitespace(&p);
        if (i < CELLS - 1) expect(&p, ',');
    }
    whitespace(&p);
    if (*p == ',') { ++p; whitespace(&p); }
    if (*p || hq[0] != 1 || hq[1] != 1) fail("terrain needs exactly one HQ per team and 160 cells");
    group = child_named(map, "objectgroup", "units");
    for (c = group->child; c; c = c->next) {
        int x, y, team = 0, kind, gid, pos;
        if (strcmp(c->key, "object")) continue;
        if (level->count == 16) fail("too many units (max 16)");
        gid = (int)integer(attr(c, "gid"), 1, 23, "unit GID");
        kind = art_kind(gid - 1, &team);
        if (kind < 0) fail("invalid unit GID %d", gid);
        x = coordinate(c, "x", 0, 240);
        y = coordinate(c, "y", 16, 160) - 1;
        if (coordinate(c, "width", 16, 16) != 1 || coordinate(c, "height", 16, 16) != 1)
            fail("units must be 16x16");
        if (*attr(c, "rotation")) (void)coordinate(c, "rotation", 0, 0);
        pos = y * 16 + x;
        if (occupied[pos] || (kind != 4 && move_cost[level->terrain[pos]] == 255))
            fail("units overlap or ground unit starts on impassable terrain");
        occupied[pos] = 1;
        level->units[0][level->count] = (uint8_t)x;
        level->units[1][level->count] = (uint8_t)y;
        level->units[2][level->count] = (uint8_t)kind;
        level->units[3][level->count++] = (uint8_t)team;
        teams |= 1 << team;
    }
    if (level->count < 2 || teams != 3) fail("place 2..16 units with both teams represented");
    free(text);
    free_nodes();
}

#endif
