/*
 *   This file is part of Auralquiz
 *   Copyright 2011-2017  JanKusanagi JRR <jancoding@gmx.com>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA .
 */

#include "ranking.h"

Ranking::Ranking(uint totalPlayers, QStringList playerNames, QList<int> playerScores,
                 QList<int> playerGood, QList<int> playerBad, QList<int> playerTimedOut,
                 QWidget *parent) : QWidget(parent)
{
    this->setWindowTitle(tr("Game ended"));
    this->setWindowIcon(QIcon::fromTheme("games-highscores"));
    this->setWindowFlags(Qt::Dialog);
    this->setWindowModality(Qt::ApplicationModal);
    this->setMinimumSize(740, 520);

    mainLabel = new QLabel(tr("All questions done!")
                           + "<br>"
                           + tr("Thanks for playing!")
                           + "<h2>= " + tr("Ranking") + " =</h2>",
                           this);
    mainLabel->setTextFormat(Qt::RichText);
    mainLabel->setAlignment(Qt::AlignHCenter);

    //QIcon::fromTheme("format-list-ordered")

    rankingTable = new QTableWidget(totalPlayers, 5, this);
    rankingTable->setHorizontalHeaderLabels(QStringList(tr("Player"))
                                                     << tr("Score")
                                                     << tr("Good")
                                                     << tr("Bad")
                                                     << tr("T.O.",
                                                           "Timed out abbreviation"));
    rankingTable->setEditTriggers(QTableWidget::NoEditTriggers); // NO editing!!
    rankingTable->setTabKeyNavigation(false); // No TAB key, so UI can be navigated
    rankingTable->setSizePolicy(QSizePolicy::MinimumExpanding,
                                QSizePolicy::MinimumExpanding);
    // eomer's suggestions
    rankingTable->setSelectionMode(QAbstractItemView::NoSelection);
    rankingTable->setFocusPolicy(Qt::NoFocus);
    rankingTable->setShowGrid(false);
    rankingTable->setAlternatingRowColors(true);


    this->normalRowHeight = 0; // Real value acquired in resizeEvent()


    // Sort player/score pairs
    for (uint counter = 0; counter < totalPlayers; ++counter)
    {
        for (uint counter2 = 0; counter2 < totalPlayers; ++counter2)
        {
            if (playerScores[counter] > playerScores[counter2])
            {
                playerNames.swap(counter, counter2);
                playerScores.swap(counter, counter2);
                playerGood.swap(counter, counter2);
                playerBad.swap(counter, counter2);
                playerTimedOut.swap(counter, counter2);
            }
        }
    }


    // Fill the table
    for (uint numPlayer = 0; numPlayer < totalPlayers; ++numPlayer)
    {
        rankingTable->setItem(numPlayer, 0,
                              new QTableWidgetItem(QIcon::fromTheme("games-highscores"),
                                                   playerNames.at(numPlayer), 0));
        rankingTable->item(numPlayer, 0)->setTextAlignment(Qt::AlignHCenter
                                                         | Qt::AlignVCenter);

        QString scoreString = QString("%1 ").arg(playerScores.at(numPlayer));
        rankingTable->setItem(numPlayer, 1,
                              new QTableWidgetItem(scoreString, 0));
        rankingTable->item(numPlayer, 1)->setTextAlignment(Qt::AlignRight
                                                         | Qt::AlignVCenter);

        QString goodString = QString("%1 ").arg(playerGood.at(numPlayer));
        rankingTable->setItem(numPlayer, 2,
                              new QTableWidgetItem(goodString, 0));
        rankingTable->item(numPlayer, 2)->setTextAlignment(Qt::AlignRight
                                                         | Qt::AlignVCenter);

        QString badString = QString("%1 ").arg(playerBad.at(numPlayer));
        rankingTable->setItem(numPlayer, 3,
                              new QTableWidgetItem(badString, 0));
        rankingTable->item(numPlayer, 3)->setTextAlignment(Qt::AlignRight
                                                         | Qt::AlignVCenter);

        QString timedOutString = QString("%1 ").arg(playerTimedOut.at(numPlayer));
        rankingTable->setItem(numPlayer, 4,
                              new QTableWidgetItem(timedOutString, 0));
        rankingTable->item(numPlayer, 4)->setTextAlignment(Qt::AlignRight
                                                         | Qt::AlignVCenter);
    }


    commentsLabel = new QLabel(this);
    commentsLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);


    if (playerScores.at(0) == 0)  // if EVERYONE has zero points
    {
        if (totalPlayers > 1)
        {
            commentsLabel->setText(tr("What?? Zero points!!\n"
                                      "You're all sooo bad!",
                                      "Plural, all players"));
        }
        else
        {
            commentsLabel->setText(tr("Zero points!\n"
                                      "%1, you're very bad!!",
                                      "%1 is the name of a player")
                                   .arg(playerNames.at(0)));
        }
    }
    else
    {
        QString comments; // FIXME for 1.1: add variety of comments

        if (totalPlayers > 1)
        {
            if (playerScores.at(0) == playerScores.at(1))
            {
                // P1 and P2 draw

                comments = tr("Draw between %1 and %2!",
                              "%1 and %2 are player names")
                            .arg(playerNames.at(0))
                            .arg(playerNames.at(1));
            }
            else
            {
                if (playerScores.at(0) > playerScores.at(1)*2 // p1 doubling p2
                 && playerScores.at(1) > 0) // and p2 having more than 0 points
                {
                    comments = tr("You're very good!!");  // doubled 2nd player's score
                }
                else
                {
                    comments = tr("You're good!");   // just won
                }
            }
            commentsLabel->setText(tr("Congratulations, %1!!",
                                      "%1 is the name of the winner")
                                   .arg(playerNames.at(0))
                                   + "\n\n"
                                   + comments);
        }
        else  // on single player
        {
            if (playerBad.at(0) == 0 && playerTimedOut.at(0) == 0)
            {
                commentsLabel->setText(tr("That was amazing!!"));
            }
            else if (playerGood.at(0) > playerBad.at(0) + playerTimedOut.at(0))
            {
                commentsLabel->setText(tr("That was quite good!"));
            }
            else
            {
                commentsLabel->setText(tr("You can do better..."));
            }
        }
    }


    bottomLayout = new QHBoxLayout();
    bottomLayout->addSpacing(8);
    bottomLayout->addWidget(rankingTable);
    bottomLayout->addSpacing(16);
    bottomLayout->addWidget(commentsLabel);
    bottomLayout->addSpacing(8);



    closeButton = new QPushButton(QIcon::fromTheme("dialog-ok"),
                                  tr("&OK"),
                                  this);
    connect(closeButton, SIGNAL(clicked()),
            this, SLOT(close()));



    mainLayout = new QVBoxLayout();
    mainLayout->addWidget(mainLabel);
    mainLayout->addSpacing(16);
    mainLayout->addLayout(bottomLayout);
    mainLayout->addSpacing(16);
    mainLayout->addWidget(closeButton, 0, Qt::AlignRight);

    this->setLayout(mainLayout);

    qDebug() << "Ranking created";
}



Ranking::~Ranking()
{
    qDebug() << "Ranking destroyed";
}




// Close event emmits a signal, to automatically get back to menu screen
void Ranking::closeEvent(QCloseEvent *event)
{
    qDebug() << "Closing Ranking";

    emit closed();

    event->accept();
}


// Resize the columns (0,1) to the width of the widget
// minus the width of the vertical header (1, 2, 3, etc), so it fits nicely
void Ranking::resizeEvent(QResizeEvent *event)
{
    int totalColumnWidth = rankingTable->width()
                           - rankingTable->verticalHeader()->width()
                           - 6;
    int playerColumnWidth = (totalColumnWidth/10) * 4; // 4 10ths
    int otherColumnsWidth = (totalColumnWidth - playerColumnWidth) / 4; // the rest

    qDebug() << "RankingTable width():" << rankingTable->width();
    qDebug() << "RankingTable verticalHeader().width():"
             << rankingTable->verticalHeader()->width();
    qDebug() << "Ranking totalColumnWidth:" << totalColumnWidth;
    qDebug() << "Ranking playerColumnWidth:" << playerColumnWidth;
    qDebug() << "Ranking otherColumnsWidth:" << otherColumnsWidth;


    if (normalRowHeight == 0) // on first resize only
    {
        normalRowHeight = rankingTable->rowHeight(0);
    }

    qDebug() << "Ranking rowHeight:" << normalRowHeight;
    qDebug() << "\n";

    rankingTable->setColumnWidth(0, playerColumnWidth);
    rankingTable->setColumnWidth(1, otherColumnsWidth);
    rankingTable->setColumnWidth(2, otherColumnsWidth);
    rankingTable->setColumnWidth(3, otherColumnsWidth);
    rankingTable->setColumnWidth(4, otherColumnsWidth);

    rankingTable->setRowHeight(0, normalRowHeight + 30);
    rankingTable->setRowHeight(1, normalRowHeight + 20);
    rankingTable->setRowHeight(2, normalRowHeight + 10);


    event->accept();
}
