// mainWindow.cpp
#include "mainWindow.h"
#include <ctime>

const int MainWindow::CARDS_NUM = 7;

MainWindow::MainWindow()
{
    higherButton = new QPushButton("Higher");
    lowerButton = new QPushButton("Lower");
    newGameButton = new QPushButton("New Game");
    
    highLowLayout = new QBoxLayout(QBoxLayout::LeftToRight);
    highLowLayout->addWidget(newGameButton);
    highLowLayout->addStretch(1);
    highLowLayout->addWidget(higherButton);
    highLowLayout->addWidget(lowerButton);
    highLowLayout->addStretch(1);
    highLowLayout->addWidget(&scoreLabel);
    
    scoreLabel.setText( QString::number(score) );
    
    buttons.setLayout(highLowLayout);

    QBoxLayout* mainLayout = new QBoxLayout(QBoxLayout::TopToBottom);
    
    mainLayout->addWidget(cards.getWidget());
    mainLayout->addWidget(&buttons);
    mainLayout->addWidget(&status);
    
    mainWindow.setLayout(mainLayout);
    
    QObject::connect(newGameButton,SIGNAL(clicked()),SLOT(newGame()));
    QObject::connect(higherButton,SIGNAL(clicked()),SLOT(higher()));
    QObject::connect(lowerButton,SIGNAL(clicked()),SLOT(lower()));
}

MainWindow::~MainWindow()
{
	if (currentDeck != 0) delete[] currentDeck; 
}

int * generateDeck()
{
    srand(time(0));
    int * deck = new int[52];
    for (int i{}; i<52; i++) deck[i] = i;
    
    for (int i{51}; i>0; i--)
        std::swap( deck[i], deck[ rand() % i ] );
    
    return deck;
}

int compareCards(int a, int b)
{
    int mod_a = a % 13;
    int mod_b = b % 13;
    if (mod_a > mod_b) return 1;
    if (mod_a < mod_b) return -1;
    if (a > b) return 1;
    else return -1;
    return 0;
}

void MainWindow::updateScore(int n)
{
    score+= n;
    scoreLabel.setText( QString::number(score) );
}


void MainWindow::higher() { newMove(1); }

void MainWindow::lower() { newMove(-1); }

void MainWindow::newMove(int n)
{
    if(!gameRunning) return;
    cards.setCard(currentCard,currentDeck[currentCard]);
    if (compareCards(currentDeck[currentCard],currentDeck[currentCard - 1]) == n)
    {
        status.setText("RIGHT!");
        updateScore(10);
    }
    else
    {
        status.setText("WRONG!");
        updateScore(-10);
    }
    if (++currentCard >= CARDS_NUM) gameRunning = false;
}

void MainWindow::newGame()
{
    cards.clear();
   
    if (currentDeck != 0) delete[] currentDeck;
    currentDeck = generateDeck();
    cards.setCard(0,currentDeck[0]);
    currentCard = 1;
    
    gameRunning = true;
    updateScore(-35);
    status.setText("New game started!");
}