#include <gui.h>
#include <gui/checkbox.h>
#include <gui_private.h>
#include <gfx.h>
#include <stdbool.h>

struct sprite gui_checkbox_sprite;

static int render(const struct gui_common *const g)
{
    const struct gui_checkbox *const c = (const struct gui_checkbox *)g;

    sprite_get_or_ret(s, -1);

    if (sprite_clone(&gui_checkbox_sprite, s))
        return -1;

    gui_coords(g, &s->x, &s->y);
    s->w /= 2;

    if (c->active)
        s->u += s->w;

    sprite_sort(s);
    return 0;
}

static void get_dim(const struct gui_common *const g,
    short *const w, short *const h)
{
    *w = gui_checkbox_sprite.w / 2;
    *h = gui_checkbox_sprite.h;
}

static int update(struct gui_common *const g,
    const union peripheral *const p, const struct camera *const cam,
    struct input *const in)
{
    struct gui_checkbox *const c = (struct gui_checkbox *)g;
    short w, h;

    get_dim(g, &w, &h);

    if (gui_pressed(g, in, p, cam, w, h))
    {
        c->active ^= true;

        if (c->on_pressed)
            c->on_pressed(c->active, c->arg);
    }

    return 0;
}

void gui_checkbox_init(struct gui_checkbox *const c)
{
    static const struct gui_common_cb cb =
    {
        .get_dim = get_dim,
        .update = update,
        .render = render
    };

    *c = (const struct gui_checkbox)
    {
        .common =
        {
            .cb = &cb
        }
    };
}
