#include "loginwindow.h"
#include "gameinstance.h"
#include "recordmanager.h"
#include "ui_loginwindow.h"

#include <sstream>

using std::ostringstream;

LoginWindow::LoginWindow(QWidget *parent):
    QMainWindow(parent),
    ui(new Ui::LoginWindow),
    rm(new RecordManager()),
    current_level(1),
    started(false)
{
    ui -> setupUi(this);
}

LoginWindow::~LoginWindow()
{
    delete rm;
    delete ui;
}

void LoginWindow::set_statusbar_text(string str)
{
    ui -> statusBar -> showMessage(QString::fromStdString(str));
}

void LoginWindow::refresh_background()
{
    ostringstream buf;
    buf << "#centralWidget { border-image: url(\":/resources/images/login_pic/level_" << current_level << ".png\"); }";
    ui -> centralWidget -> setStyleSheet(QString::fromStdString(buf.str()));
}

void LoginWindow::start_game()
{
    game = new GameInstance(current_level, rm -> get_record(current_level));
    connect(game, SIGNAL(game_over()), this, SLOT(game_closed()));
}

void LoginWindow::game_closed()
{
    started = false;
    if (game -> get_result() != -1) {
        rm -> update_record(current_level, game -> get_result());
    }
    delete game;
}

void LoginWindow::switch_stage(int inc)
{
    int new_level = current_level + inc;
    if (new_level < 1) {
        set_statusbar_text("You are already at the minimal level.");
    } else if (new_level > rm -> get_num_of_levels()) {
        set_statusbar_text("You are already at the maximal level.");
    } else if (new_level != 1 && rm -> get_record(new_level - 1) == -1) {
        set_statusbar_text("You can not move to the next level before passing this level.");
    } else {
        current_level = new_level;
        refresh_background();
        set_statusbar_text("");
    }
}

void LoginWindow::on_prev_button_clicked()
{
    if (!started) {
        switch_stage(-1);
    }
}

void LoginWindow::on_next_button_clicked()
{
    if (!started) {
        switch_stage(1);
    }
}

void LoginWindow::on_start_button_clicked()
{
    if (!started) {
        start_game();
        started = true;
    }
}
