#include <game.h>
#include <game_private.h>
#include <gfx.h>
#include <human_player.h>
#include <player.h>
#include <system.h>
#include <terrain.h>
#include <stddef.h>

int game(const struct game_cfg *const cfg)
{
    int ret = -1;
    enum {MAP_RESOURCES = 3};
    struct human_player human;
    struct terrain_map map;

    if (terrain_init(cfg->map, &map))
    {
        fprintf(stderr, "%s: terrain_init failed\n", __func__);
        return -1;
    }

    const struct human_player_cfg hcfg =
    {
        .p = cfg->p,
        .dim =
        {
            .w = MAP_W,
            .h = MAP_H,
        },

        .pl =
        {
            .team = PLAYER_COLOR_BLUE,
            .x = 80,
            .y = 40
        }
    };

    if (human_player_init(&hcfg, &human))
        goto end;

    bool exit = false;

    while (!exit)
    {
        system_loop();

        if (human.pl.alive)
        {
            struct player_others o;

            human_player_update(&human, &o);
            exit |= human.periph->common.exit;
            terrain_update(&map);

            if (terrain_render(&map, &human.cam)
                || human_player_render(&human, &o))
                goto end;

            /* TODO: render AI players. */
        }

        instance_cyclic();

        if (gfx_draw())
            goto end;
    }

    ret = 0;

end:
    return ret;
}
