#include "ui/hotseat_prebattle/prebattlescene.h"

#include "player.h"
#include "playermanager.h"
#include "race.h"
#include "racemanager.h"

#include "hotseatgame/gameproperties.h"

#include "gui/guiscenemanager.h"
#include "ui_prebattlescene.h"

PreBattleScene::PreBattleScene(QWidget *parent) :
    Scene(parent),
    ui(new Ui::PreBattleScene)
{
    ui->setupUi(this);
    watcher = new ButtonEventListener(this);
    ui->to_battle_button->installEventFilter(watcher);
}

PreBattleScene::~PreBattleScene()
{
    delete ui;
}

void PreBattleScene::init() {
    for (unsigned i = 0; i < GameProperties::PLAYERS_NUMBER; i++) {

        Player* player = PlayerManager::getInstance().getPlayer(i);

        QLabel* name = findChild<QLabel*>("player_" + QString::number(i) + "_name");
        if (name)
            name->setText(player->getPlayerName());

        QLabel* race = findChild<QLabel*>("player_" + QString::number(i) + "_race");
        if (race)
            race->setText("<img src=\":/assets/units/" + player->getRace()->getRaceId() + "/icon.png\" width=\"80\" height=\"80\"/>");

        auto units = player->getUnitsAsVector();
        for (unsigned unit_number = 0; unit_number < units.size(); unit_number++) {
            QLabel* unit_icon = findChild<QLabel*>("player_" + QString::number(i) + "_chosen_unit_" + QString::number(unit_number));
            if (!unit_icon) {
                continue;
            }
            QString race_name = player->getRace()->getRaceId();
            QString unit_name = units[unit_number]->getUnitId();
            unit_icon->setText("<img src=\":/assets/units/" + race_name + "/" + unit_name + "/icon.png\" width=\"58\" height=\"58\"/>");
        }

        for (unsigned unit_number = units.size(); unit_number < GameProperties::MAX_PARTY_SIZE; unit_number++) {
            QLabel* unit_icon = findChild<QLabel*>("player_" + QString::number(i) + "_chosen_unit_" + QString::number(unit_number));
            if (!unit_icon) {
                continue;
            }
            unit_icon->hide();
        }

        QWidget* units_widget = findChild<QWidget*>("player_" + QString::number(i) + "_units");
        if (units_widget)
            units_widget->resize(70 * units.size(), 70);
    }
}

void PreBattleScene::on_to_battle_button_clicked()
{
    GuiSceneManager::getInstance().changeScene("hotseatgame");
}
