#include <menu.h>
#include <menu_private.h>
#include <camera.h>
#include <game.h>
#include <gfx.h>
#include <input.h>
#include <peripheral.h>
#include <settings.h>
#include <system.h>
#include <stdbool.h>

void menu_on_pressed(void *const arg)
{
    *(bool *)arg = true;
}

int menu_update(struct menu_common *const c,
    int (*update)(struct menu_common *, void *),
    int (*render)(const struct menu_common *, void *),
    void *const arg)
{
    system_loop();
    peripheral_update(&c->p);
    input_update(&c->in, &c->p);
    camera_update(&c->cam, &c->p, &c->in);

    if (update && update(c, arg))
        return -1;

    rect_get_or_ret(r, -1);
    rect_init(r);
    r->w = screen_w;
    r->h = screen_h;
    rect_sort(r);

    if (render && render(c, arg))
    {
        fprintf(stderr, "%s: render cb failed\n", __func__);
        return -1;
    }
    else if (input_render(&c->in, &c->p))
    {
        fprintf(stderr, "%s: input_render failed\n", __func__);
        return -1;
    }

    switch (c->p.common.type)
    {
        case PERIPHERAL_TYPE_PAD:
            /* Fall through. */
        case PERIPHERAL_TYPE_KEYBOARD_MOUSE:
            if (cursor_render(&c->cam.cursor))
                return -1;

            break;

        case PERIPHERAL_TYPE_TOUCH:
            break;
    }

    if (gfx_draw())
    {
        fprintf(stderr, "%s: gfx_draw failed\n", __func__);
        return -1;
    }

    return 0;
}

int menu(void)
{
    struct peripheral_cfg cfg;
    struct menu_common c = {0};

    peripheral_get_default(&cfg);

    if (game_resinit())
        return -1;

    cursor_init(&c.cam.cursor);
    peripheral_init(&cfg, &c.p);
    settings_load("settings.ini", &c.s);

#if 1

    struct game_cfg gcfg =
    {
        .map = "city1.txt",
        .p = &c.p
    };

    return game(&gcfg);
#else
    return menu_main(&c);
#endif
}
