#include <assert.h>
#include <stdio.h>

#include "tileset.h"

Tileset TILESET_INVALID = {.isValid = false};

Tileset tilesetCreate(const TilesetDesc *desc) {
    Tileset tileset = {};
    cute_tiled_tileset_t *source = desc->source;

    char pathBuffer[256];
    // auto terminates
    snprintf(pathBuffer, sizeof(pathBuffer), "%s%s%s",
             desc->assetDir ? desc->assetDir : "",
             desc->assetDir ? "/" : "",
             source->image.ptr);

    tileset.tiles = LoadTexture(pathBuffer);
    tileset.startID = source->firstgid;
    tileset.tileWidth = source->tilewidth;
    tileset.tileHeight = source->tileheight;

    tileset.offsetX = source->tileoffset_x;
    tileset.offsetY = source->tileoffset_y;

    tileset.width = tileset.tiles.width / tileset.tileWidth;
    tileset.height = tileset.tiles.height / tileset.tileHeight;

    if (tileset.tiles.width != source->imagewidth ||
        tileset.tiles.height != source->imageheight) {
        tilesetDestroy(&tileset);
        return TILESET_INVALID;
    }

    tileset.isValid = true;
    return tileset;
}

Rectangle tilesetGetTileRegion(Tileset *tileset, int tileID) {
    tileID = tileID - tileset->startID;
    int posX = tileID % tileset->width;
    int posY = tileID / tileset->width;
    return (Rectangle) {posX * tileset->tileWidth, posY * tileset->tileHeight,
                        tileset->tileWidth, tileset->tileHeight};
}

void tilesetDestroy(Tileset *tileset) {
    UnloadTexture(tileset->tiles);
    *tileset = TILESET_INVALID;
}

