#include "mainlib.h"
#include "ui_menu.h"
#include <pthread.h>

Game::Game()
{
    al_set_new_window_title("Just Dance! Game");
    al_set_new_display_refresh_rate(fr);
    al_set_new_display_flags(ALLEGRO_WINDOWED);
    game = al_create_display(gw, gh);

    Element mA1("media/mA1.png");
    Element mA2("media/mA3.png");
    Element mA3("media/mA5.png");
    Element mA4("media/mA7.png");

    if (game == nullptr)
    {
            perror("Error reservando display.\n");
            exit(-1);
    }

    if (!al_show_mouse_cursor(game) || !al_set_system_mouse_cursor(game, ALLEGRO_SYSTEM_MOUSE_CURSOR_ARROW))
    {
            perror("Error mostrando cursor.\n");
            exit(-1);
    }

    queue = al_create_event_queue();
    if (queue == nullptr)
    {
            perror("Error creando cola de eventos.\n");
            exit(-1);
    }

    al_register_event_source(queue, al_get_keyboard_event_source());
    al_register_event_source(queue, al_get_mouse_event_source());

    elements = (Element *)malloc(sizeof(Element) * 4);

    *elements = mA1;
    *(elements + 1) = mA2;
    *(elements + 2) = mA3;
    *(elements + 3) = mA4;

    background = new Background("media/background.png");
}

Game::~Game()
{
    al_destroy_event_queue(queue);
    al_destroy_display(game);
}


void menu::game_start()
{
    sscanf((ui->resolution->currentText()).toStdString().c_str(), "%d%d", &gw, &gh);
    sscanf((ui->framerate->currentText()).toStdString().c_str(), "%d", &fr);

    ui->centralwidget->setEnabled(false);

    pthread_create(&game_thread, NULL, game_loop, this);
}

void menu::game_return()
{
    pthread_join(game_thread, NULL);
    ui->centralwidget->setEnabled(true);
}

void * game_loop(void * arg)
{
    Allegro al;
    Game g;

    bool flag = true;

    do
    {
        g.draw();

        al_wait_for_event(g.queue, &g.in_event);
        switch (g.in_event.type)
        {
            case ALLEGRO_KEY_DOWN:
                switch (g.in_event.keyboard.keycode) {
                    case ALLEGRO_KEY_ESCAPE:
                        flag = false;
                    break;
                }
                break;
        }
    } while(flag);

    emit ((menu *)arg)->game_ended();

    sleep(1);

    pthread_exit(NULL);
}

void Game::draw()
{
    al_set_target_backbuffer(game);
    al_clear_to_color(al_map_rgb(255, 255, 255));

    background->draw(0, 0);

    elements[0].draw(gh * 3 / 5, gh * 7 / 16, gh / 8, gh / 8);
    elements[1].draw(gh * 7 / 16, gh * 3 / 5, gh / 8, gh / 8);
    elements[2].draw(gh * 11 / 40, gh * 7 / 16, gh / 8, gh / 8);
    elements[3].draw(gh * 7 / 16, gh * 11 / 40, gh / 8, gh / 8);

    al_flip_display();
}
