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

#include <cute_tiled.h>

#include "tileset.h"

BzTileset BZ_TILESET_INVALID = {.isValid = false};

BzTileset bzTilesetCreate(const BzTilesetDesc *desc) {
    BzTileset tileset = {};
    cute_tiled_tileset_t *source = cute_tiled_load_external_tileset(desc->path, NULL);

    tileset.tiles = LoadTexture(desc->texturePath);
    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;

    cute_tiled_free_external_tileset(source);

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

    tileset.isValid = true;
    return tileset;
}

Rectangle bzTilesetGetTileRegion(BzTileset *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 bzTilesetDestroy(BzTileset *tileset) {
    UnloadTexture(tileset->tiles);
    *tileset = BZ_TILESET_INVALID;
}

