/* 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. */

#ifndef BOARD_H
#define BOARD_H

#include <QDeclarativeView>

#include "piece.h"  // TODO How to use foreward declaration for class enum

class Player;
class QDeclarativeItem;

class Board : public QDeclarativeView
{
    Q_OBJECT

public:
    Board(QWidget *parent = 0);
    ~Board();

public slots:
    void newGame();

public:
    void clearBoard();
    void clearPlayers();
    void endGame();

    Player * getCurrentPlayer() const;
    Player * getNextPlayer() const;
    Player * getPlayer(Piece::Color color) const;
    int getMoveCount() const;
    Piece * getPiece(const QString &squareName) const;
    QList<Piece *> getPieces(Piece::Color color) const;

signals:
    void gameStarted();
    void whiteMoveStarted();
    void whiteMoveEnded();
    void blackMoveStarted();
    void blackMoveEnded();
    void check();
    void checkMate();
    void staleMate();

private slots:
    void pieceClicked();
    void squareClicked(const QString &squareName);

private:
    void turnEnd();

    bool isSquareNameValid(const QString &squareName) const;
    QDeclarativeItem * getSquare(const QString &squareName) const;

    Piece * addPiece(Piece::Type type, Piece::Color color, const QString &squareName);
    bool removePiece(Piece *piece);

    bool isPieceAllowedToMove(const Piece &piece);
    bool isPieceMoveAllowed(const Piece &piece, const QString &destinationSquareName) const;

    bool movePiece(Piece &piece, const QString &destinationSquareName);
    bool movePiece(const QString &sourceSquareName, const QString &destinationSquareName);
    void checkCastlingRule(Piece &piece, const QString &destinationSquareName);

    Player *m_whitePlayer;
    Player *m_blackPlayer;
    QList<Piece *> m_boardPieces;
    QHash<QString, Piece *> m_pieceOfSquare;

    int m_movesCount;
    Piece * m_movingPiece;

    bool isWhiteMoving;
    bool m_gameEnded;
};

#endif // BOARD_H
