#include <menu.h>
#include <menu_private.h>
#include <gui.h>
#include <gui/button.h>
#include <gui/container.h>
#include <gui/checkbox.h>
#include <gui/label.h>
#include <stdbool.h>

struct menu_hostjoin
{
    struct gui_container cnt;
    struct gui_button local, host, join, back;
};

static int update(struct menu_common *const c, void *const arg)
{
    struct menu_hostjoin *const m = arg;

    if (gui_update(&m->cnt.common, &c->p, &c->cam, &c->in))
        return -1;

    return 0;
}

static int render(const struct menu_common *const c, void *const arg)
{
    const struct menu_hostjoin *const m = arg;

    if (gui_render(&m->cnt.common))
        return -1;

    return 0;
}

static void init_header_gui(struct menu_hostjoin *const m, bool *const local,
    bool *const host, bool *const join)
{
    {
        struct gui_container *const c = &m->cnt;

        gui_container_init(c);
        c->common.hcentered = true;
        c->common.vcentered = true;
        c->spacing = 4;
        c->mode = GUI_CONTAINER_MODE_V;
    }

    {
        struct gui_button *const b = &m->local;

        gui_button_init(b, GUI_BUTTON_TYPE_1);
        b->u.type1.label.text = "Local game";
        b->common.hcentered = true;
        b->u.type1.w = 140;
        b->arg = local;
        b->on_pressed = menu_on_pressed;
        gui_add_child(&m->cnt.common, &b->common);
    }

    {
        struct gui_button *const b = &m->host;

        gui_button_init(b, GUI_BUTTON_TYPE_1);
        b->u.type1.label.text = "Host game";
        b->common.hcentered = true;
        b->u.type1.w = 140;
        b->arg = host;
        b->on_pressed = menu_on_pressed;
        gui_add_child(&m->cnt.common, &b->common);
    }

    {
        struct gui_button *const b = &m->join;

        gui_button_init(b, GUI_BUTTON_TYPE_1);
        b->u.type1.label.text = "Join game";
        b->common.hcentered = true;
        b->u.type1.w = 140;
        b->arg = join;
        b->on_pressed = menu_on_pressed;
        gui_add_child(&m->cnt.common, &b->common);
    }
}

static void init_footer_gui(struct menu_hostjoin *const m, bool *const back)
{
    struct gui_button *const b = &m->back;

    gui_button_init(b, GUI_BUTTON_TYPE_1);
    b->u.type1.label.text = "Back";
    b->common.hcentered = true;
    b->u.type1.w = 140;
    b->arg = back;
    b->on_pressed = menu_on_pressed;
    gui_add_child(&m->cnt.common, &b->common);
}

int menu_hostjoin(struct menu_common *const c)
{
    bool back = false;

    do
    {
        struct menu_hostjoin m;
        bool local = false, host = false, join = false;

        init_header_gui(&m, &local, &host, &join);
        init_footer_gui(&m, &back);

        while (!back && !c->p.common.exit && !local && !host && !join)
            if (menu_update(c, update, render, &m))
                return -1;

        if (host && menu_host(c))
            return -1;
        else if (join && menu_join(c))
            return -1;

    } while (!back && !c->p.common.exit);

    return 0;
}
