public HistoryViewModel(int? playerId)
            : this()
        {
            if (playerId != null)
            {
                using (IGameDataService dataService = new GameDataService())
                {
                    IEnumerable<DB.Match> playingMatches = dataService.GetAllMatchesForPlayer(playerId.Value);
                    foreach (var match in playingMatches)
                    {
                        DB.Player opponent = dataService.GetPlayer(match.PlayerOneId == playerId ? match.PlayerTwoId : match.PlayerOneId);
                        DB.Game currentGame = dataService.GetGame(match.CurrentGameId.Value);
                        DB.Player winningPlayer = null;
                        if (match.WinningPlayerId != null)
                            winningPlayer = dataService.GetPlayer(match.WinningPlayerId.Value);

                        HistoryViewModel.History history = new History();
                        history.MatchId = match.MatchId;
                        history.OpponentName = opponent.PlayerName;
                        history.Winner = winningPlayer != null ? winningPlayer.PlayerName : "none";
                        history.EndDate = match.EndDate;
                        history.StartDateTime = match.CreateDate;

                        this.Histories.Add(history);
                    }
                }
            }
        }
        public CurrentGamesViewModel(int? playerId)
            : this()
        {
            if (playerId != null)
            {
                using (IGameDataService dataService = new GameDataService())
                {
                    IEnumerable<DB.Match> playingMatches = dataService.GetPlayingMatchesForPlayer(playerId.Value);
                    foreach (var match in playingMatches)
                    {
                        DB.Player opponent = dataService.GetPlayer(match.PlayerOneId == playerId ? match.PlayerTwoId : match.PlayerOneId);
                        DB.Game currentGame = dataService.GetGame(match.CurrentGameId.Value);
                        DB.Player currentPlayer = null;
                        if (currentGame.CurrentPlayerId != null)
                            currentPlayer = dataService.GetPlayer(currentGame.CurrentPlayerId.Value);

                        CurrentGamesViewModel.Game game = new Game();
                        game.MatchId = match.MatchId;
                        game.OpponentName = opponent.PlayerName;
                        game.PlayerTurn = currentPlayer != null ? currentPlayer.PlayerName : "none";
                        game.StartDateTime = match.CreateDate;

                        this.Games.Add(game);
                    }
                }
            }
        }
        void ICommunicationChannel.ChallengePlayer(int matchId)
        {
            using (IGameDataService dataService = new GameDataService())
            {
                //We need to create a session even if the challenge isn't accepted.
                Match match = dataService.GetMatch(matchId, null);
                dataService.CreateCentralServerSession(match.CurrentGameId.Value);

                Player player = dataService.GetPlayer(match.PlayerOneId);
                Player opponent = dataService.GetPlayer(match.PlayerTwoId);
                Game game = dataService.GetGame(match.CurrentGameId.Value);

                var requestData = new ChallengeRequest();
                requestData.PlayerName = player.PlayerName;
                requestData.OpponentName = opponent.PlayerName;

                string requestJSON = JsonSerializer.SerializeToJSON<ChallengeRequest>(requestData);
                var requestConfig = new ServerRequestConfig();
                requestConfig.Url = string.Format("{0}/ServerPairing.php", ConfigurationManager.AppSettings["CentralServerUrl"]);
                requestConfig.RequestData = requestJSON;
                requestConfig.GameId = game.GameId;
                requestConfig.MatchId = game.MatchId;
                requestConfig.ResponseAction = new Action<string, int>(ChallengePlayerCompleted);

                this.PerformServerRequest(requestConfig);
            }
        }
        private void UpdateGame(int gameId)
        {
            using (IGameDataService gameDataService = new GameDataService())
            {
                Game game = gameDataService.GetGame(gameId);
                GameState state = this.GetGameState(gameId, game.PlayerOneId);
                int gameWon = this.IsWon(state.GameBoard);
                if (gameWon == 1 || gameWon == -1)
                {
                    if (gameWon == 1)
                        gameDataService.EndGame(gameId, game.PlayerOneId);
                    else if (gameWon == -1)
                        gameDataService.EndGame(gameId, game.PlayerTwoId);
                }

                if (!game.DeathMatchMode)
                {
                    int ninthCheckPlayer = game.CurrentPlayerId == game.PlayerOneId ? 1 : -1;
                    bool canWinWithNinth = false;
                    for (int x = 0; x < 3; x++)
                    {
                        for (int y = 0; y < 3; y++)
                        {
                            if ((state.GameBoard[x][y] == null || state.GameBoard[x][y] == 0)
                                && this.CanWin(state.GameBoard, ninthCheckPlayer, x, y) == ninthCheckPlayer)
                            {
                                canWinWithNinth = true;
                                goto FoundEmpty;
                            }
                        }
                    }

                FoundEmpty:
                    if (!canWinWithNinth)
                    {
                        gameDataService.setToDeathMatch(game.GameId);
                    }
                }

                gameDataService.Save();
            }
            using (IGameDataService gameDataService = new GameDataService())
            {
                gameDataService.SwapPlayerTurn(gameId);
                gameDataService.Save();
            }
        }
 /// <summary>
 /// Checks if the game has been updated.
 /// </summary>
 /// <param name="gameId">The id of the game being played.</param>
 /// <param name="stateDateString">String format of the last known game state, in yyyyMMddHHmmss format.</param>
 /// <returns></returns>
 public bool IsGameStateChaged(int gameId, string stateDateString)
 {
     using (IGameDataService gameDataService = new GameDataService())
     {
         Game game = gameDataService.GetGame(gameId);
         if(game != null)
             return game.StateDate.ToString("yyyyMMddHHmmssfffff") != stateDateString;
         return false;
     }
 }
        public GameState GetGameState(int gameId, int playerId)
        {
            GameState result = null;
            using (IGameDataService gameDataService = new GameDataService())
            {
                Game game = gameDataService.GetGame(gameId);
                //The game exists, so we definately have a state to pass back.
                if (game != null)
                {
                    result = new GameState();
                    if (game.CurrentPlayerId == null && game.WonDate == null && game.EndDate == null)
                        result.Mode = PlayMode.None;
                    else if (game.WonDate == null && game.EndDate == null)
                        result.Mode = PlayMode.Playing;
                    else if (game.WonDate != null)
                        result.Mode = PlayMode.Won;
                    else
                        result.Mode = PlayMode.Ended;

                    result.GameBoard = new int?[3][]
                                        {
                                            new int?[3],
                                            new int?[3],
                                            new int?[3]
                                        };
                    IEnumerable<GameMove> moves = gameDataService.GetGameMoves(gameId).OrderBy(move => move.MoveDate).ToList();
                    foreach (var move in moves)
                    {
                        if (move.IsSettingPiece)
                            result.GameBoard[move.X][move.y] = move.PlayerId == playerId ? 1 : -1;
                        else
                            result.GameBoard[move.X][move.y] = null;
                    }

                    if (result.GameBoard.Sum(row => row.Count(cell => cell == null || cell == 0)) <= 1 && result.Mode == PlayMode.Playing)
                    {
                        if (game.DeathMatchMode)
                            result.Mode = PlayMode.DeathMatch;
                    }

                    result.StateDateString = game.StateDate.ToString("yyyyMMddHHmmssfffff");
                    result.YourTurn = game.CurrentPlayerId == playerId;

                    if (game.WinningPlayerId != null)
                    {
                        Player winner = gameDataService.GetPlayer(game.WinningPlayerId.Value);
                        result.YouWon = playerId == game.WinningPlayerId;
                        result.WinningPlayerName = winner.PlayerName;
                    }
                }
            }
            return result;
        }