/* Copyright (c) (2012) (Gauthier Brion) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */

#include "board.h"

#include "pawn.h"
#include "rook.h"
#include "knight.h"
#include "bishop.h"
#include "queen.h"
#include "king.h"
#include "player.h"
#include <QDeclarativeItem>
#include <QPoint>
#include <QVector>

Board::Board(QWidget *parent) :
    QDeclarativeView(QUrl("qrc:/board.qml"), parent),
    m_whitePlayer(new Player(Piece::White, *this, this)),
    m_blackPlayer(new Player(Piece::Black, *this, this)),
    m_movesCount(0),
    m_movingPiece(NULL)
{
    connect(rootObject(), SIGNAL(squareClicked(QString)), this, SLOT(squareClicked(QString)));
}

Board::~Board()
{
    clearBoard();
}

void Board::newGame()
{
    // Remove all remaining pieces
    clearBoard();

    // Clear player informations
    clearPlayers();

    // Create white pieces
    addPiece(Piece::Pawn, Piece::White, "a2");
    addPiece(Piece::Pawn, Piece::White, "b2");
    addPiece(Piece::Pawn, Piece::White, "c2");
    addPiece(Piece::Pawn, Piece::White, "d2");
    addPiece(Piece::Pawn, Piece::White, "e2");
    addPiece(Piece::Pawn, Piece::White, "f2");
    addPiece(Piece::Pawn, Piece::White, "g2");
    addPiece(Piece::Pawn, Piece::White, "h2");
    addPiece(Piece::Rook, Piece::White, "a1");
    addPiece(Piece::Knight, Piece::White, "b1");
    addPiece(Piece::Bishop, Piece::White, "c1");
    addPiece(Piece::Queen, Piece::White, "d1");
    addPiece(Piece::King, Piece::White, "e1");
    addPiece(Piece::Bishop, Piece::White, "f1");
    addPiece(Piece::Knight, Piece::White, "g1");
    addPiece(Piece::Rook, Piece::White, "h1");

    // Create black pieces
    addPiece(Piece::Pawn, Piece::Black, "a7");
    addPiece(Piece::Pawn, Piece::Black, "b7");
    addPiece(Piece::Pawn, Piece::Black, "c7");
    addPiece(Piece::Pawn, Piece::Black, "d7");
    addPiece(Piece::Pawn, Piece::Black, "e7");
    addPiece(Piece::Pawn, Piece::Black, "f7");
    addPiece(Piece::Pawn, Piece::Black, "g7");
    addPiece(Piece::Pawn, Piece::Black, "h7");
    addPiece(Piece::Rook, Piece::Black, "a8");
    addPiece(Piece::Knight, Piece::Black, "b8");
    addPiece(Piece::Bishop, Piece::Black, "c8");
    addPiece(Piece::Queen, Piece::Black, "d8");
    addPiece(Piece::King, Piece::Black, "e8");
    addPiece(Piece::Bishop, Piece::Black, "f8");
    addPiece(Piece::Knight, Piece::Black, "g8");
    addPiece(Piece::Rook, Piece::Black, "h8");

    m_gameEnded = false;

    emit gameStarted();
    isWhiteMoving = true;
    emit whiteMoveStarted();
}

void Board::clearBoard()
{
    while (!m_boardPieces.isEmpty())
        delete m_boardPieces.takeFirst();

    m_pieceOfSquare.clear();

    m_movesCount = 0;
    m_movingPiece = NULL;
    isWhiteMoving = true;
}

void Board::clearPlayers()
{
    m_whitePlayer->clear();
    m_blackPlayer->clear();
}

void Board::endGame()
{
    m_gameEnded = true;
}

int Board::getMoveCount() const
{
    return m_movesCount;
}

void Board::pieceClicked()
{
    if (m_gameEnded)
        return;

    Piece *piece = qobject_cast<Piece *>(sender());
    if (!piece) return;

    if (!m_movingPiece)
    {
        if (isPieceAllowedToMove(*piece))
        {
            m_movingPiece = piece;
            // TODO Check if there is at least one valid move
            m_movingPiece->setSelectedState(true);
        }
    }
    else
    {
        squareClicked(piece->getMySquareName());
    }
}

void Board::squareClicked(const QString &squareName)
{
    bool turnEnded = false;

    if (!m_movingPiece) return;

    if (isPieceMoveAllowed(*m_movingPiece, squareName))
        turnEnded = movePiece(*m_movingPiece, squareName);

    m_movingPiece->setSelectedState(false);
    m_movingPiece = NULL;

    // TODO Add promotion possibility if the piece is at the top and if its a pawn

    if (turnEnded)
    {
        ++m_movesCount;
        turnEnd();
    }
}

void Board::turnEnd()
{
    bool isNextPlayerCheck = getNextPlayer()->isCheck() != NULL;
    bool isNextPlayerStuck = getNextPlayer()->isStuck(); // Search if the next player can do at least one move
    bool isNextPlayerStaleMate = !isNextPlayerCheck && isNextPlayerStuck;
    bool isNextPlayerCheckMate = isNextPlayerCheck && isNextPlayerStuck;

    isWhiteMoving?emit whiteMoveEnded():emit blackMoveEnded();

    if (isNextPlayerCheckMate)
    {
        emit checkMate();
        endGame();
        return;
    }

    if (isNextPlayerStaleMate)
    {
        emit staleMate();
        endGame();
        return;
    }

    if (isNextPlayerCheck)
    {
        emit check();
    }

    isWhiteMoving = !isWhiteMoving;
    isWhiteMoving?emit whiteMoveStarted():emit blackMoveStarted();
}

Player * Board::getCurrentPlayer() const
{
    if(isWhiteMoving)
        return m_whitePlayer;
    else
        return m_blackPlayer;
}

Player *Board::getNextPlayer() const
{
    if(isWhiteMoving)
        return m_blackPlayer;
    else
        return m_whitePlayer;
}

Player *Board::getPlayer(Piece::Color color) const
{
    if (color == Piece::White)
        return m_whitePlayer;
    else
        return m_blackPlayer;
}

bool Board::isSquareNameValid(const QString &squareName) const
{
    const QString letters = "abcdefgh";
    const QString numbers = "12345678";

    if (squareName.length() == 2
            && letters.contains(squareName.at(0).toLower())
            && numbers.contains(squareName.at(1)))
        return true;

    return false;
}

QDeclarativeItem * Board::getSquare(const QString &squareName) const
{
    if (!isSquareNameValid(squareName)) return NULL;

    QObject *squareObject = rootObject()->findChild<QObject *>(squareName);
    QDeclarativeItem *square = qobject_cast<QDeclarativeItem *>(squareObject);

    if (!square) qDebug("CRITICAL Board::getSquare : Can't find the square \"%s\" !", qPrintable(squareName));

    return square;
}

Piece * Board::addPiece(Piece::Type type, Piece::Color color, const QString &squareName)
{
    QDeclarativeItem *square = getSquare(squareName);
    Piece *piece;

    switch (type)
    {
    case Piece::Pawn:
        piece = new Pawn(color, *this, square);
        break;
    case Piece::Rook:
        piece = new Rook(color, *this, square);
        break;
    case Piece::Knight:
        piece = new Knight(color, *this, square);
        break;
    case Piece::Bishop:
        piece = new Bishop(color, *this, square);
        break;
    case Piece::Queen:
        piece = new Queen(color, *this, square);
        break;
    case Piece::King:
        piece = new King(color, *this, square);
        break;
    }

    if (piece)
    {
        m_boardPieces << piece;
        m_pieceOfSquare[squareName] = piece;
        connect(piece, SIGNAL(clicked()), this, SLOT(pieceClicked()));
    }

    return piece;
}

bool Board::removePiece(Piece *piece)
{
    if (piece)
    {
        m_boardPieces.removeOne(piece);
        m_pieceOfSquare.remove(piece->getMySquareName());
        piece->deleteLater();
    }

    return true;
}

Piece * Board::getPiece(const QString &squareName) const
{
    if (!isSquareNameValid(squareName)) return NULL;

    return m_pieceOfSquare.value(squareName, NULL);
}

QList<Piece *> Board::getPieces(Piece::Color color) const
{
    QList<Piece *> pieces;

    foreach (Piece *piece, m_boardPieces)
        if (piece->getColor() == color)
            pieces << piece;

    return pieces;
}

bool Board::isPieceAllowedToMove(const Piece &piece)
{
    // Check if the piece is one of the playing player
    bool isWhitePiece = piece.getColor() == Piece::White;
    if (isWhitePiece ^ isWhiteMoving)
        return false;

    // Check if the piece has at least one move allowed
    if (piece.getAllowedDestinations().isEmpty())
        return false;

    return true;
}

bool Board::isPieceMoveAllowed(const Piece &piece, const QString &destinationSquareName) const
{
    if (!isSquareNameValid(destinationSquareName)) return false;

    const Piece *destinationPiece = getPiece(destinationSquareName);

    // Check if the destination square is not occupied by one piece of the same color
    if (destinationPiece && destinationPiece->getColor() == piece.getColor())
        return false;

    // Check if the destination square is allowed theorically
    if (!piece.getAllowedDestinations().contains(destinationSquareName))
        return false;

    // Check if this move will not put ourself in check
    //if (getCurrentPlayer()->isCheck())
//        return false;

    return true;
}

bool Board::movePiece(Piece &piece, const QString &destinationSquareName)
{
    // Get/Check destination square
    QDeclarativeItem *destinationSquare = getSquare(destinationSquareName);
    if (!destinationSquare) return false;

    // Check delete of piece, etc...
    Piece *destinationPiece = getPiece(destinationSquareName);
    if (destinationPiece) removePiece(destinationPiece);

    // Move the piece
    m_pieceOfSquare.remove(piece.getMySquareName());
    m_pieceOfSquare[destinationSquareName] = &piece;
    piece.move(destinationSquare);

    // Check castling
    checkCastlingRule(piece, destinationSquareName);

    return true;
}

bool Board::movePiece(const QString &sourceSquareName, const QString &destinationSquareName)
{
    // Get/Check the piece from source square
    Piece *sourcePiece = getPiece(sourceSquareName);
    if (!sourcePiece) return false;

    return movePiece(*sourcePiece, destinationSquareName);
}

void Board::checkCastlingRule(Piece &piece, const QString &destinationSquareName)
{
    if (piece.getType() == Piece::King)
    {
        Piece *rook;
        QString rookDestinationSquareName;
        if (destinationSquareName == "c1")
        {
            rook = getPiece("a1");
            rookDestinationSquareName = "d1";
        }
        else if (destinationSquareName == "g1")
        {
            rook = getPiece("h1");
            rookDestinationSquareName = "f1";
        }
        else if (destinationSquareName == "c8")
        {
            rook = getPiece("a8");
            rookDestinationSquareName = "d8";
        }
        else if (destinationSquareName == "g8")
        {
            rook = getPiece("h8");
            rookDestinationSquareName = "f8";
        }
        else
            rook = NULL;

        if (rook)
            movePiece(*rook, rookDestinationSquareName);
    }
}
