#include <building.h>
#include <camera.h>
#include <gfx.h>
#include <stdbool.h>
#include <stddef.h>

struct sprite building_sprites[1];

int building_render(const struct building *const b,
    const struct camera *const cam, const bool sel)
{
    if (!b->instance.alive)
        return 0;

    sprite_get_or_ret(s, -1);

    if (sprite_clone(&building_sprites[b->type], s))
        return -1;

    const struct instance_render_cfg cfg =
    {
        .i = &b->instance,
        .prim_type = INSTANCE_RENDER_CFG_SPRITE,
        .prim = {.s = s},
        .cam = cam,
        .sel = sel
    };

    return instance_render(&cfg);
}

static void get_dimensions(const enum building_type type, short *const w,
    short *const h)
{
    static const struct dim
    {
        short w, h;
    } dim[1];

    const struct dim *const d = &dim[type];
    *w = d->w;
    *h = d->h;
}

static void *op;
static void (*cb)(const struct util_rect *, bool, void *);

void building_create(const struct building_cfg *const cfg,
    struct building *const b)
{
    struct instance *const i = &b->instance;

    get_dimensions(cfg->type, &i->r.w, &i->r.h);
    b->type = cfg->type;
    i->r.x = cfg->x;
    i->r.y = cfg->y;
    i->alive = true;

    if (cb)
        cb(&i->r, i->alive, op);
}

void building_set_alive_cb(void (*const f)(const struct util_rect *, bool, void *),
    void *const p)
{
    cb = f;
    op = p;
}

const char *building_str(const struct building *const b)
{
    static const char *const str[1];

    return str[b->type];
}
