/// <summary>
 /// updates the penalty box DB with new information
 /// </summary>
 /// <param name="game"></param>
 /// <param name="cachedGame"></param>
 /// <param name="db"></param>
 /// <param name="pen"></param>
 public static void updatePenaltyBoxInDb(GameViewModel game, ManagementContext db, SkaterInPenaltyBoxViewModel pen, DataModels.Game.Game g)
 {
     try
     {
         var cachedPen = g.GameMemberPenaltyBox.Where(x => x.PenaltyIdFromGame == pen.PenaltyId).FirstOrDefault();
         if (cachedPen == null)
             insertNewPenaltyIntoDb(game, db, pen, g);
         else
         {
             cachedPen.GameTimeMilliSecondsReturned = pen.GameTimeInMillisecondsReleased;
             cachedPen.GameTimeMilliSecondsSent = pen.GameTimeInMillisecondsSent;
             cachedPen.JamNumberReturned = pen.JamNumberReleased;
             cachedPen.JamNumberSent = pen.JamNumberSent;
             cachedPen.JamIdReturned = pen.JamIdReleased;
             cachedPen.JamIdSent = pen.JamIdSent;
             cachedPen.JamTimeMilliSecondsReturned = pen.JamTimeInMillisecondsReleased;
             cachedPen.JamTimeMilliSecondsSent = pen.JamTimeInMillisecondsSent;
             cachedPen.PenaltyType = pen.PenaltyType.ToString();
             db.SaveChanges();
         }
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
 }
 /// <summary>
 /// gets the current line up clock for the game.
 /// </summary>
 /// <param name="id"></param>
 /// <param name="game"></param>
 /// <returns></returns>
 public  static GameStopwatch getLineUpClock(Guid id, GameViewModel game)
 {
     try
     {
         ManagementContext db = new ManagementContext();
         var getClock = (from xx in db.GameStopWatch
                         where xx.StopwatchForId == id
                         where xx.Type == (int)StopWatchTypeEnum.LineUpClock
                         select xx).FirstOrDefault();
         if (getClock != null)
         {
             game.CurrentLineUpClock = new StopwatchWrapper();
             game.CurrentLineUpClock.IsClockAtZero = getClock.IsClockAtZero == 1 ? true : false;
             game.CurrentLineUpClock.IsRunning = getClock.IsRunning == 1 ? true : false;
             game.CurrentLineUpClock.StartTime = getClock.StartDateTime;
             game.CurrentLineUpClock.TimeElapsed = getClock.TimeElapsed;
             game.CurrentLineUpClock.TimeRemaining = getClock.TimeRemaining;
             game.CurrentLineUpClock.TimerLength = getClock.Length;
         }
         return getClock;
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return null;
 }
 public static void insertScoreIntoDb(Guid teamId, GameViewModel game, ScoreViewModel score, ManagementContext db, DataModels.Game.Game g)
 {
     try
     {
         GameScore scores = new GameScore();
         if (score.CurrentDateTimeScored != new DateTime())
             scores.DateTimeScored = score.CurrentDateTimeScored;
         else
             scores.DateTimeScored = DateTime.UtcNow;
         scores.GameScoreId = score.PointId;
         scores.JamNumber = score.JamNumber;
         scores.JamId = score.JamId;
         scores.PeriodNumber = score.Period;
         scores.PeriodTimeRemainingMilliseconds = score.PeriodTimeRemaining;
         scores.Point = score.Points;
         scores.GameTeam = g.GameTeams.Where(x => x.TeamId == teamId).First();
         if (score.PlayerWhoScored != null && score.PlayerWhoScored.SkaterId != new Guid())
             scores.MemberWhoScored = g.GameTeams.Where(x => x.TeamId == teamId).First().GameMembers.Where(x => x.GameMemberId == score.PlayerWhoScored.SkaterId).FirstOrDefault();
         db.GameScore.Add(scores);
         db.SaveChanges();
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: "jamId:" + score.JamId + "/ pointId:" + score.PointId);
     }
 }
 public static int DeepCompareOfficialReviewsToDb(GameViewModel game, ManagementContext db, DataModels.Game.Game gameNew)
 {
     try
     {
         if (game.OfficialReviews != null)
         {
             foreach (var member in game.OfficialReviews)
             {
                 var review = gameNew.OfficialReviews.Where(x => x.OfficialReviewIdFromGame == member.OfficialReviewId).FirstOrDefault();
                 if (review == null)
                     AddOfficialReview(game, gameNew, member);
                 else
                 {
                     review.TeamNumber = (byte)member.TeamNumber;
                     review.Details = member.Details;
                     review.Result = member.Result;
                 }
             }
         }
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return db.SaveChanges();
 }
        public static int insertAssistIntoDb(Guid teamId, GameViewModel game, AssistViewModel assisted, ManagementContext db, DataModels.Game.Game g)
        {
            int c = 0;
            try
            {
                GameMemberAssist assist = new GameMemberAssist();
                assist.DateTimeAssisted = assisted.CurrentDateTimeAssisted;
                assist.GameAssistId = assisted.AssistId;
                assist.JamNumber = assisted.JamNumber;
                assist.JamId = assisted.JamId;
                assist.PeriodNumber = assisted.Period;
                assist.PeriodTimeRemainingMilliseconds = assisted.PeriodTimeRemaining;
                assist.Game = g;

                assist.MemberWhoAssisted = g.GameTeams.Where(x => x.TeamId == teamId).First().GameMembers.Where(x => x.GameMemberId == assisted.PlayerWhoAssisted.SkaterId).FirstOrDefault();
                if (assist.MemberWhoAssisted != null)
                {
                    db.GameMemberAssist.Add(assist);
                    c += db.SaveChanges();
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return c;
        }
        public static void insertBlockIntoDb(Guid teamId, GameViewModel game, BlockViewModel block, ManagementContext db, DataModels.Game.Game g)
        {
            try
            {
                GameMemberBlock blocks = new GameMemberBlock();
                blocks.DateTimeBlocked = block.CurrentDateTimeBlock;
                blocks.GameBlockId = block.BlockId;
                blocks.JamNumber = block.JamNumber;
                blocks.JamId = block.JamId;
                blocks.PeriodNumber = block.Period;
                blocks.PeriodTimeRemainingMilliseconds = block.PeriodTimeRemaining;
                blocks.Game = g;

                blocks.MemberWhoBlocked = g.GameTeams.Where(x => x.TeamId == teamId).First().GameMembers.Where(x => x.GameMemberId == block.PlayerWhoBlocked.SkaterId).FirstOrDefault();
                if (blocks.MemberWhoBlocked != null)
                {
                    db.GameMemberBlock.Add(blocks);
                    db.SaveChanges();
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
        }
 public static void insertNewPenaltyIntoDb(GameViewModel game, ManagementContext db, SkaterInPenaltyBoxViewModel pen, DataModels.Game.Game g)
 {
     try
     {
         var m = GameMemberClass.getMemberOfTeamInGame(pen.PlayerSentToBox.SkaterId, g);
         if (m != null)
         {
             GameMemberPenaltyBox penalty = new GameMemberPenaltyBox();
             penalty.PenaltyNumberForSkater = pen.PenaltyNumberForSkater;
             penalty.Member = m;
             penalty.GameTimeMilliSecondsSent = pen.GameTimeInMillisecondsSent;
             penalty.GameTimeMilliSecondsReturned = pen.GameTimeInMillisecondsReleased;
             penalty.JamNumberReturned = pen.JamNumberReleased;
             penalty.JamIdReturned = pen.JamIdReleased;
             penalty.JamIdSent = pen.JamIdSent;
             penalty.JamTimeMilliSecondsReturned = pen.JamTimeInMillisecondsReleased;
             penalty.JamTimeMilliSecondsSent = pen.JamTimeInMillisecondsSent;
             penalty.Game = g;
             penalty.PenaltyIdFromGame = pen.PenaltyId;
             penalty.PenaltyType = pen.PenaltyType.ToString();
             db.GameMemberPenaltyBox.Add(penalty);
             db.SaveChanges();
         }
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
 }
        /// <summary>
        /// inserts the team into the DB.
        /// </summary>
        /// <param name="game"></param>
        /// <param name="team"></param>
        /// <param name="db"></param>
        public static void insertTeamIntoDb(GameViewModel game, TeamViewModel team, ManagementContext db, DataModels.Game.Game g)
        {
            try
            {
                DataModels.Game.GameTeam tm = new DataModels.Game.GameTeam();
                tm.Created = DateTime.UtcNow;
                tm.Game = g;
                if (String.IsNullOrEmpty(team.TeamName))
                    tm.TeamName = "Temp";
                else
                    tm.TeamName = team.TeamName;

                if (team.TeamId == new Guid())
                    tm.TeamId = Guid.NewGuid();
                else
                    tm.TeamId = team.TeamId;

                if (team.Logo != null && team.Logo.TeamLogoId != new Guid())
                {
                    var logo = db.TeamLogos.Where(x => x.TeamLogoId == team.Logo.TeamLogoId).FirstOrDefault();
                    if (logo != null)
                    {
                        tm.Logo = logo;
                        team.Logo.ImageUrl = logo.ImageUrl;
                        team.Logo.ImageUrlThumb = logo.ImageUrlThumb;
                    }
                }
                if (team.LineUpSettings != null)
                {
                    UpdateLineUpSettings(team, tm);
                }

                db.GameTeam.Add(tm);

                foreach (var member in team.TeamMembers)
                {
                    GameMemberClass.insertNewSkater(game.GameId, db, tm.TeamId, member, tm);
                }

                //TODO:record time outs left.
                db.SaveChanges();
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
        }
        /// <summary>
        /// entry point for updating the team.
        /// </summary>
        /// <param name="game"></param>
        /// <param name="team"></param>
        /// <param name="db"></param>
        public static void updateTeam(GameViewModel game, TeamViewModel team, ManagementContext db, DataModels.Game.Game g)
        {
            try
            {
                var getTeam = g.GameTeams.Where(x => x.TeamId == team.TeamId).FirstOrDefault();

                if (getTeam == null)
                {
                    insertTeamIntoDb(game, team, db, g);
                }
                else
                {

                    if (String.IsNullOrEmpty(team.TeamName))
                        getTeam.TeamName = "Temp";
                    else
                        getTeam.TeamName = team.TeamName;
                    if (team.Logo != null)
                    {
                        if ((getTeam.Logo == null) || (getTeam.Logo != null && getTeam.Logo.TeamLogoId != team.Logo.TeamLogoId))
                        {
                            var logo = db.TeamLogos.Where(x => x.TeamLogoId == team.Logo.TeamLogoId).FirstOrDefault();
                            if (logo != null)
                            {
                                getTeam.Logo = logo;
                                team.Logo.ImageUrl = logo.ImageUrl;
                                team.Logo.ImageUrlThumb = logo.ImageUrlThumb;
                            }
                        }
                    }

                    getTeam.CurrentTimeouts = team.TimeOutsLeft;
                    getTeam.LeageName = team.LeagueName;
                    if (team.LineUpSettings != null)
                    {
                        UpdateLineUpSettings(team, getTeam);
                    }

                }
                db.SaveChanges();
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: "tried to update the team");
            }
        }
 public static void AddOfficialToGame(GameViewModel game, ManagementContext db, DataModels.Game.Game gameNew, Guid skaterId, string skaterName, OfficialTypeEnum officialType, int refereeType, CertificationLevelEnum cert)
 {
     try
     {
         if (!String.IsNullOrEmpty(skaterName))
         {
             GameOfficial o = new GameOfficial();
             o.Game = gameNew;
             o.GameOfficialId = skaterId;
             o.MemberName = skaterName;
             o.OfficialTypeEnum = Convert.ToInt32(officialType);
             o.RefereeType = refereeType;
             o.CertificationLevelEnum = (byte)cert;
             db.GameOfficials.Add(o);
             db.SaveChanges();
         }
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
 }
        /// <summary>
        /// updates the team assists to the DB.
        /// </summary>
        /// <param name="team"></param>
        /// <param name="teamId"></param>
        /// <param name="game"></param>
        /// <param name="db"></param>
        /// <param name="g"></param>
        public static void updateTeamAssists(TeamNumberEnum team, Guid teamId, GameViewModel game, ManagementContext db, DataModels.Game.Game g)
        {
            try
            {
                List<AssistViewModel> assitsNew = new List<AssistViewModel>();

                if (team == TeamNumberEnum.Team1)
                    assitsNew = game.AssistsForTeam1;
                else
                    assitsNew = game.AssistsForTeam2;

                for (int i = 0; i < assitsNew.Count; i++)
                {
                    insertAssistIntoDb(teamId, game, assitsNew[i], db, g);
                }

            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: "tried updating team scores");
            }
        }
 public static void AddOfficialReview(GameViewModel game, DataModels.Game.Game gameNew, OfficialReviewViewModel review)
 {
     try
     {
         GameOfficialReview or = new GameOfficialReview();
         or.CurrentDateTimeReviewed = review.CurrentDateTimeReviewed;
         or.Details = review.Details;
         or.Game = gameNew;
         or.JamId = review.JamId;
         or.JamNumber = review.JamNumber;
         or.OfficialReviewIdFromGame = review.OfficialReviewId;
         or.Period = review.Period;
         or.PeriodTimeRemaining = review.PeriodTimeRemaining;
         or.Result = review.Result;
         or.TeamNumber = (byte)review.TeamNumber;
         gameNew.OfficialReviews.Add(or);
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
 }
 private static void UpdateOfficialToDb(GameViewModel game, ManagementContext db, DataModels.Game.Game gameNew, Guid skaterId, string skaterName, OfficialTypeEnum officialType, int refereeType, CertificationLevelEnum cert)
 {
     try
     {
         var off = db.GameOfficials.Where(x => x.GameOfficialId == skaterId).FirstOrDefault();
         if (off != null && !String.IsNullOrEmpty(skaterName))
         {
             off.Game = gameNew;
             off.MemberName = skaterName;
             off.OfficialTypeEnum = Convert.ToInt32(officialType);
             off.RefereeType = refereeType;
             off.CertificationLevelEnum = (byte)cert;
         }
         else
         {
             AddOfficialToGame(game, db, gameNew, skaterId, skaterName, officialType, refereeType, cert);
         }
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
 }
        public static int DeepCompareOfficialsToDb(GameViewModel game, ManagementContext db, DataModels.Game.Game gameNew)
        {
            try
            {
                if (game.Officials != null)
                {
                    foreach (var member in game.Officials.Nsos)
                    {
                        UpdateOfficialToDb(game, db, gameNew, member.SkaterId, member.SkaterName, OfficialTypeEnum.NSO, Convert.ToInt32(member.RefereeType), member.Cert);
                    }
                    foreach (var member in game.Officials.Referees)
                    {
                        UpdateOfficialToDb(game, db, gameNew, member.SkaterId, member.SkaterName, OfficialTypeEnum.Referee, Convert.ToInt32(member.RefereeType), member.Cert);
                    }

                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return db.SaveChanges();
        }
        /// <summary>
        /// updates the team blocks to the Db.
        /// </summary>
        /// <param name="team"></param>
        /// <param name="teamId"></param>
        /// <param name="game"></param>
        /// <param name="db"></param>
        /// <param name="g"></param>
        public static void updateTeamBlocks(TeamNumberEnum team, Guid teamId, GameViewModel game, ManagementContext db, DataModels.Game.Game g)
        {
            try
            {
                List<BlockViewModel> blocksNew = new List<BlockViewModel>();

                if (team == TeamNumberEnum.Team1)
                    blocksNew = game.BlocksForTeam1;
                else
                    blocksNew = game.BlocksForTeam2;

                for (int i = 0; i < blocksNew.Count; i++)
                {
                    var blockDb = g.GameMemberBlocks.Where(x => x.GameBlockId == new Guid("c88dd0c2-2e9e-4e0f-b6db-98d39b913291")).FirstOrDefault();

                    if (blockDb == null)
                        insertBlockIntoDb(teamId, game, blocksNew[i], db, g);
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: "tried updating team scores");
            }
        }
        /// <summary>
        /// updates the team penalties to the DB.
        /// </summary>
        /// <param name="team"></param>
        /// <param name="teamId"></param>
        /// <param name="game"></param>
        /// <param name="db"></param>
        /// <param name="g"></param>
        public static void updateTeamPenalties(TeamNumberEnum team, Guid teamId, GameViewModel game, ManagementContext db, DataModels.Game.Game g)
        {
            try
            {
                List<PenaltyViewModel> blocksNew = new List<PenaltyViewModel>();

                if (team == TeamNumberEnum.Team1 && game.PenaltiesForTeam1 != null)
                    blocksNew = game.PenaltiesForTeam1;
                else if (team == TeamNumberEnum.Team1 && game.PenaltiesForTeam2 != null)
                    blocksNew = game.PenaltiesForTeam2;

                for (int i = 0; i < blocksNew.Count; i++)
                {
                    var blockDb = g.GameMemberPenalties.Where(x => x.GamePenaltyId == blocksNew[i].PenaltyId).FirstOrDefault();

                    if (blockDb == null)
                        insertPenaltyIntoDb(teamId, game, blocksNew[i], db, g);
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: "tried updating team scores");
            }
        }
        public static GameViewModel getGameFromDb(Guid id)
        {
            try
            {
                ManagementContext db = new ManagementContext();
                var getGame = (from xx in db.Games.Include("GameLinks").Include("GameMemberPenalties").Include("GameMemberAssists").Include("GameMemberBlocks").Include("GameTeams").Include("GameJams").Include("GamePolicy").Include("GameScores").Include("GameTimeouts").Include("GameTeams.Logo")
                               where xx.GameId == id
                               //game must be published to be used.

                               //where xx.IsGamePublishedOnline == true
                               select xx).FirstOrDefault();

                if (getGame == null)
                    return null;
                GameViewModel game = new GameViewModel();

                if (getGame.GameTournament != null)
                {
                    game.TournamentId = getGame.GameTournament.TournamentId;
                    game.TournamentName = getGame.GameTournament.TournamentName;
                }
                if (getGame.FederationOwners.Count > 0)
                {
                    game.FederationId = getGame.FederationOwners.FirstOrDefault().Federation.FederationId;
                    game.FederationName = getGame.FederationOwners.FirstOrDefault().Federation.Name;
                }
                if (getGame.SelectedShop != null)
                    game.SelectedShop = getGame.SelectedShop.MerchantId.ToString();
                game.IsThereVideoOfGame = (GameVideoTypeEnum)Enum.Parse(typeof(GameVideoTypeEnum), getGame.IsThereVideoOfGame.ToString());
                game.StreamingUrlOfVideo = getGame.StreamingUrlOfVideo;
                game.StreamingUrlOfVideoMobile = getGame.StreamingUrlOfVideoMobile;
                game.EmbededVideoHtml = getGame.EmbededVideoHtml;
                game.LastModified = DateTime.UtcNow;
                game.IdForOnlineManagementUse = getGame.IdForOnlineManagementUse;
                game.ElapsedTimeGameClockMilliSeconds = (long)getGame.ElapsedGameTimeInMilliseconds;
                game.GameDate = getGame.GameDate;
                game.GameEndDate = getGame.GameEndDate;
                game.GameId = id;
                game.GameName = getGame.GameName;
                game.HasGameEnded = getGame.IsGameOver;
                game.HasGameStarted = getGame.HasGameStarted;
                game.GameLocation = getGame.GameLocation;
                game.PublishGameOnline = getGame.IsGameLive;
                game.SaveGameOnline = getGame.IsGameScrimmage;
                GameClock.getPeriodClock(id, game);
                GameClock.getIntermissionClock(id, game);
                GameClock.getLineUpClock(id, game);
                GameClock.getTimeOutClock(id, game);
                if (getGame.Paywall != null)
                    game.PaywallId = getGame.Paywall.PaywallId;


                if (getGame.ScoreboardType == 0)
                    game.ScoreboardMode = ScoreboardModeEnum.Debug;
                else if (getGame.ScoreboardType == 1)
                    game.ScoreboardMode = ScoreboardModeEnum.Live;

                //we order the teams so the first one in, is also the first one out.
                var getTeams = getGame.GameTeams.OrderByDescending(x => x.Created).ToList();
                if (game.ScoresTeam1 == null)
                    game.ScoresTeam1 = new List<ScoreViewModel>();
                if (game.ScoresTeam2 == null)
                    game.ScoresTeam2 = new List<ScoreViewModel>();

                game.GameLinks = new List<GameLinkViewModel>();
                var gameLinkss = getGame.GameLinks.ToList();
                for (int i = 0; i < getGame.GameLinks.Count; i++)
                {
                    GameLinkViewModel gameLink = new GameLinkViewModel();
                    gameLink.GameLink = gameLinkss[i].Link;
                    gameLink.LinkId = gameLinkss[i].GameLinkId;
                    gameLink.LinkType = (GameLinkTypeEnum)Enum.ToObject(typeof(GameLinkTypeEnum), gameLinkss[i].LinkType);
                    game.GameLinks.Add(gameLink);
                }


                for (int i = 0; i < getTeams.Count; i++)
                {
                    TeamViewModel tvm = new TeamViewModel();
                    tvm.TeamId = getTeams[i].TeamId;
                    tvm.Logo = new Portable.Classes.Team.TeamLogo();

                    tvm.TeamLinkId = getTeams[i].TeamIdLink;
                    var dc = new ManagementContext();
                    if (getTeams[i].Logo != null)
                    {
                        tvm.Logo.ImageUrl = getTeams[i].Logo.ImageUrl;
                        tvm.Logo.TeamLogoId = getTeams[i].Logo.TeamLogoId;
                    }

                    tvm.TeamName = getTeams[i].TeamName;
                    tvm.TimeOutsLeft = getTeams[i].CurrentTimeouts;
                    tvm.TeamMembers = new System.Collections.ObjectModel.ObservableCollection<TeamMembersViewModel>();
                    if (i == 0)
                    {
                        game.CurrentTeam1Score = getTeams[i].CurrentScore;
                        game.Team1 = tvm;
                    }
                    else if (i == 1)
                    {
                        game.CurrentTeam2Score = getTeams[i].CurrentScore;
                        game.Team2 = tvm;
                    }


                    foreach (var mem in getTeams[i].GameMembers)
                    {
                        TeamMembersViewModel mvm = new TeamMembersViewModel();
                        mvm.SkaterId = mem.GameMemberId;
                        mvm.SkaterName = mem.MemberName;
                        mvm.SkaterNumber = mem.MemberNumber;
                        mvm.SkaterLinkId = mem.MemberLinkId;

                        if (getTeams[i].TeamId == game.Team1.TeamId)
                            game.Team1.TeamMembers.Add(mvm);
                        else if (getTeams[i].TeamId == game.Team2.TeamId)
                            game.Team2.TeamMembers.Add(mvm);
                    }
                    //scores must come after teams  members get added.
                    var scores = getTeams[i].GameScores.OrderBy(x => x.JamNumber);
                    foreach (var score in scores)
                    {
                        try
                        {
                            ScoreViewModel svm = new ScoreViewModel(score.Point, score.PeriodTimeRemainingMilliseconds, score.JamId, score.JamNumber, score.PeriodNumber, score.DateTimeScored, score.GameScoreId);

                            if (getTeams[i].TeamId == game.Team1.TeamId)
                            {
                                if (score.MemberWhoScored != null)
                                    svm.PlayerWhoScored = game.Team1.TeamMembers.Where(x => x.SkaterId == score.MemberWhoScored.GameMemberId).FirstOrDefault();
                                game.ScoresTeam1.Add(svm);
                            }
                            else if (getTeams[i].TeamId == game.Team2.TeamId)
                            {
                                if (score.MemberWhoScored != null)
                                    svm.PlayerWhoScored = game.Team2.TeamMembers.Where(x => x.SkaterId == score.MemberWhoScored.GameMemberId).FirstOrDefault();
                                game.ScoresTeam2.Add(svm);
                            }
                        }
                        catch (Exception exception)
                        {
                            ErrorDatabaseManager.AddException(exception, exception.GetType());
                        }
                    }


                }
                game.BlocksForTeam1 = new List<BlockViewModel>();
                game.BlocksForTeam2 = new List<BlockViewModel>();
                game.AssistsForTeam1 = new List<AssistViewModel>();
                game.AssistsForTeam2 = new List<AssistViewModel>();
                game.PenaltiesForTeam1 = new List<PenaltyViewModel>();
                game.PenaltiesForTeam2 = new List<PenaltyViewModel>();
                //blocks must come after teams  members get added.
                var blocks = getGame.GameMemberBlocks.OrderBy(x => x.JamNumber);
                foreach (var block in blocks)
                {
                    try
                    {
                        BlockViewModel svm = new BlockViewModel(block.PeriodTimeRemainingMilliseconds, block.JamNumber, block.PeriodNumber, block.DateTimeBlocked, block.GameBlockId);

                        var member = game.Team1.TeamMembers.Where(x => x.SkaterId == block.MemberWhoBlocked.GameMemberId).FirstOrDefault();
                        if (member == null)
                        {
                            member = game.Team2.TeamMembers.Where(x => x.SkaterId == block.MemberWhoBlocked.GameMemberId).FirstOrDefault();
                            svm.PlayerWhoBlocked = member;
                            game.BlocksForTeam2.Add(svm);
                        }
                        else
                        {
                            svm.PlayerWhoBlocked = member;
                            game.BlocksForTeam1.Add(svm);
                        }
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                }

                //blocks must come after teams  members get added.
                var assists = getGame.GameMemberAssists.OrderBy(x => x.JamNumber);
                foreach (var assist in assists)
                {
                    try
                    {
                        AssistViewModel svm = new AssistViewModel(assist.PeriodTimeRemainingMilliseconds, assist.JamNumber, assist.PeriodNumber, assist.DateTimeAssisted, assist.GameAssistId);

                        var member = game.Team1.TeamMembers.Where(x => x.SkaterId == assist.MemberWhoAssisted.GameMemberId).FirstOrDefault();
                        if (member == null)
                        {
                            member = game.Team2.TeamMembers.Where(x => x.SkaterId == assist.MemberWhoAssisted.GameMemberId).FirstOrDefault();
                            svm.PlayerWhoAssisted = member;
                            game.AssistsForTeam2.Add(svm);
                        }
                        else
                        {
                            svm.PlayerWhoAssisted = member;
                            game.AssistsForTeam1.Add(svm);
                        }
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                }

                var penal = getGame.GameMemberPenalties.OrderBy(x => x.JamNumber);
                foreach (var pen in penal)
                {
                    try
                    {
                        PenaltyViewModel svm = new PenaltyViewModel((PenaltiesEnum)Enum.Parse(typeof(PenaltiesEnum), pen.PenaltyType.ToString()), pen.PeriodTimeRemainingMilliseconds, pen.JamNumber, pen.PeriodNumber, pen.DateTimePenaltied, pen.GamePenaltyId);

                        var member = game.Team1.TeamMembers.Where(x => x.SkaterId == pen.MemberWhoPenaltied.GameMemberId).FirstOrDefault();
                        if (member == null)
                        {
                            member = game.Team2.TeamMembers.Where(x => x.SkaterId == pen.MemberWhoPenaltied.GameMemberId).FirstOrDefault();
                            svm.PenaltyAgainstMember = member;
                            game.PenaltiesForTeam2.Add(svm);
                        }
                        else
                        {
                            svm.PenaltyAgainstMember = member;
                            game.PenaltiesForTeam1.Add(svm);
                        }
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                }

                var getJams = getGame.GameJams.OrderBy(x => x.JamNumber).ToList();
                var getJamClocks = (from xx in db.GameStopWatch
                                    where xx.StopwatchForId == id
                                    where xx.Type == (int)StopWatchTypeEnum.JamClock
                                    select xx).ToList();

                foreach (var jam in getJams)
                {
                    try
                    {
                        JamViewModel jvm = new JamViewModel(jam.JamNumber, jam.GameTimeElapsedMillisecondsStart, jam.CurrentPeriod);
                        var scoresT1 = game.ScoresTeam1.Where(x => x.JamNumber == jam.JamNumber);
                        foreach (var score in scoresT1)
                            jvm.TotalPointsForJamT1 += score.Points;

                        var scoresT2 = game.ScoresTeam2.Where(x => x.JamNumber == jam.JamNumber);
                        foreach (var score in scoresT2)
                            jvm.TotalPointsForJamT2 += score.Points;

                        var getClock = getJamClocks.Where(x => x.JamNumber == jam.JamNumber).FirstOrDefault();
                        if (getClock != null)
                        {
                            StopwatchWrapper stop = new StopwatchWrapper();
                            stop.IsClockAtZero = getClock.IsClockAtZero == 1 ? true : false;
                            stop.IsRunning = getClock.IsRunning == 1 ? true : false;
                            stop.StartTime = getClock.StartDateTime;
                            stop.TimeElapsed = getClock.TimeElapsed;
                            stop.TimeRemaining = getClock.TimeRemaining;
                            stop.TimerLength = getClock.Length;
                            jvm.JamClock = stop;
                        }

                        if (jam.Blocker1Team1 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker1Team1.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker1Team1.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker1Team1.MemberName;
                            tmvm.SkaterNumber = jam.Blocker1Team1.MemberNumber;
                            jvm.Blocker1T1 = tmvm;
                        }
                        if (jam.Blocker2Team1 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker2Team1.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker2Team1.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker2Team1.MemberName;
                            tmvm.SkaterNumber = jam.Blocker2Team1.MemberNumber;
                            jvm.Blocker2T1 = tmvm;
                        }
                        if (jam.Blocker3Team1 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker3Team1.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker3Team1.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker3Team1.MemberName;
                            tmvm.SkaterNumber = jam.Blocker3Team1.MemberNumber;
                            jvm.Blocker3T1 = tmvm;
                        }
                        if (jam.Blocker4Team1 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker4Team1.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker4Team1.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker4Team1.MemberName;
                            tmvm.SkaterNumber = jam.Blocker4Team1.MemberNumber;
                            jvm.Blocker4T1 = tmvm;
                        }
                        if (jam.PivotTeam1 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.PivotTeam1.GameMemberId;
                            tmvm.SkaterLinkId = jam.PivotTeam1.MemberLinkId;
                            tmvm.SkaterName = jam.PivotTeam1.MemberName;
                            tmvm.SkaterNumber = jam.PivotTeam1.MemberNumber;
                            jvm.PivotT1 = tmvm;
                        }
                        if (jam.JammerTeam1 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.JammerTeam1.GameMemberId;
                            tmvm.SkaterLinkId = jam.JammerTeam1.MemberLinkId;
                            tmvm.SkaterName = jam.JammerTeam1.MemberName;
                            tmvm.SkaterNumber = jam.JammerTeam1.MemberNumber;
                            jvm.JammerT1 = tmvm;
                        }
                        if (jam.Blocker1Team2 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker1Team2.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker1Team2.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker1Team2.MemberName;
                            tmvm.SkaterNumber = jam.Blocker1Team2.MemberNumber;
                            jvm.Blocker1T2 = tmvm;
                        }
                        if (jam.Blocker2Team2 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker2Team2.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker2Team2.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker2Team2.MemberName;
                            tmvm.SkaterNumber = jam.Blocker2Team2.MemberNumber;
                            jvm.Blocker2T2 = tmvm;
                        }
                        if (jam.Blocker3Team2 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker3Team2.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker3Team2.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker3Team2.MemberName;
                            tmvm.SkaterNumber = jam.Blocker3Team2.MemberNumber;
                            jvm.Blocker3T2 = tmvm;
                        }
                        if (jam.Blocker4Team2 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.Blocker4Team2.GameMemberId;
                            tmvm.SkaterLinkId = jam.Blocker4Team2.MemberLinkId;
                            tmvm.SkaterName = jam.Blocker4Team2.MemberName;
                            tmvm.SkaterNumber = jam.Blocker4Team2.MemberNumber;
                            jvm.Blocker4T2 = tmvm;
                        }
                        if (jam.PivotTeam2 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.PivotTeam2.GameMemberId;
                            tmvm.SkaterLinkId = jam.PivotTeam2.MemberLinkId;
                            tmvm.SkaterName = jam.PivotTeam2.MemberName;
                            tmvm.SkaterNumber = jam.PivotTeam2.MemberNumber;
                            jvm.PivotT2 = tmvm;
                        }
                        if (jam.JammerTeam2 != null)
                        {
                            TeamMembersViewModel tmvm = new TeamMembersViewModel();
                            tmvm.SkaterId = jam.JammerTeam2.GameMemberId;
                            tmvm.SkaterLinkId = jam.JammerTeam2.MemberLinkId;
                            tmvm.SkaterName = jam.JammerTeam2.MemberName;
                            tmvm.SkaterNumber = jam.JammerTeam2.MemberNumber;
                            jvm.JammerT2 = tmvm;
                        }

                        //gets all the lead jammers for this particular jam.
                        var getLeadJammers = jam.LeadJammers.ToList();
                        foreach (var lJam in getLeadJammers)
                        {
                            try
                            {
                                if (lJam.GameMemberId != new Guid())
                                {
                                    LeadJammerViewModel ljvm = new LeadJammerViewModel();
                                    ljvm.GameTimeInMilliseconds = lJam.GameTimeInMilliseconds;
                                    ljvm.Jammer = new TeamMembersViewModel();
                                    ljvm.Jammer.SkaterId = lJam.GameMemberId;
                                    ljvm.JamTimeInMilliseconds = lJam.JamTimeInMilliseconds;
                                    ljvm.GameLeadJamId = lJam.GameJamLeadId;
                                    jvm.LeadJammers.Add(ljvm);
                                }
                            }
                            catch (Exception exception)
                            { ErrorDatabaseManager.AddException(exception, exception.GetType()); }
                        }

                        game.Jams.Add(jvm);
                    }
                    catch (Exception exception)
                    { ErrorDatabaseManager.AddException(exception, exception.GetType()); }
                }


                var Penalties = getGame.GameMemberPenaltyBox.ToList();

                for (int i = 0; i < Penalties.Count; i++)
                {
                    SkaterInPenaltyBoxViewModel skater = new SkaterInPenaltyBoxViewModel();
                    skater.GameTimeInMillisecondsReleased = Penalties[i].GameTimeMilliSecondsReturned;
                    skater.GameTimeInMillisecondsSent = Penalties[i].GameTimeMilliSecondsSent;
                    skater.JamNumberReleased = Penalties[i].JamNumberReturned;
                    skater.JamNumberSent = Penalties[i].JamNumberSent;
                    skater.JamTimeInMillisecondsReleased = Penalties[i].JamTimeMilliSecondsReturned;
                    skater.JamTimeInMillisecondsSent = Penalties[i].JamTimeMilliSecondsSent;
                    skater.PenaltyId = Penalties[i].PenaltyIdFromGame;
                    skater.PenaltyScale = (PenaltyScaleEnum)Enum.ToObject(typeof(PenaltyScaleEnum), (int)Penalties[i].PenaltyScale);
                    skater.PenaltyType = (PenaltiesEnum)Enum.Parse(typeof(PenaltiesEnum), Penalties[i].PenaltyType);
                    skater.PenaltyNumberForSkater = Penalties[i].PenaltyNumberForSkater;
                    bool checkIfPenaltyIsAssigned = false;


                    for (int j = 0; j < game.Team1.TeamMembers.Count; j++)
                    {
                        if (game.Team1.TeamMembers[j].SkaterId == Penalties[i].Member.GameMemberId)
                        {
                            skater.PlayerSentToBox = game.Team1.TeamMembers[j];
                            game.Team1.TeamMembers[j].Penalties.Add(new PenaltyViewModel(skater.PenaltyType));
                            checkIfPenaltyIsAssigned = true;
                            break;
                        }
                    }
                    if (!checkIfPenaltyIsAssigned)
                    {
                        for (int j = 0; j < game.Team2.TeamMembers.Count; j++)
                        {
                            if (game.Team2.TeamMembers[j].SkaterId == Penalties[i].Member.GameMemberId)
                            {
                                skater.PlayerSentToBox = game.Team2.TeamMembers[j];
                                game.Team2.TeamMembers[j].Penalties.Add(new PenaltyViewModel(skater.PenaltyType));
                                checkIfPenaltyIsAssigned = true;
                                break;
                            }
                        }
                    }

                    game.PenaltyBox.Add(skater);
                }

                var getPolicies = getGame.GamePolicy;
                if (getPolicies != null)
                {
                    if (game.Policy == null)
                        game.Policy = PolicyViewModel.Instance;
                    game.Policy.AdChangeAutomaticallyChangeImage = getPolicies.AdChangeAutomaticallyChangeImage == 0 ? false : true;
                    game.Policy.AdChangeDisplayChangesInMilliSeconds = (long)getPolicies.AdChangeDisplayChangesInMilliSeconds;
                    game.Policy.AdChangeShowAdsDuringIntermission = getPolicies.AdChangeShowAdsDuringIntermission == 0 ? false : true;
                    game.Policy.AdChangeShowAdsRandomly = getPolicies.AdChangeShowAdsRandomly == 0 ? false : true;
                    game.Policy.AdChangeUseLineUpClock = getPolicies.AdChangeUseLineUpClock == 0 ? false : true;
                    game.Policy.AlwaysShowJamClock = getPolicies.AlwaysShowJamClock == 0 ? false : true;
                    game.Policy.EnableAdChange = getPolicies.EnableAdChange == 0 ? false : true;
                    game.Policy.EnableIntermissionNaming = getPolicies.EnableIntermissionNaming == 0 ? false : true;
                    game.Policy.EnableIntermissionStartOfClock = getPolicies.EnableIntermissionStartOfClock == 0 ? false : true;
                    game.Policy.FirstIntermissionNameConfirmedText = getPolicies.FirstIntermissionNameConfirmedText;
                    game.Policy.FirstIntermissionNameText = getPolicies.FirstIntermissionNameText;
                    game.Policy.GameSelectionType = (GameTypeEnum)Enum.Parse(typeof(GameTypeEnum), getPolicies.GameSelectionType);
                    game.Policy.HideClockTimeAfterBout = getPolicies.HideClockTimeAfterBout == 0 ? false : true;
                    game.Policy.IntermissionOtherText = getPolicies.IntermissionOtherText;
                    game.Policy.IntermissionStartOfClockInMilliseconds = (long)getPolicies.IntermissionStartOfClockInMilliseconds;
                    game.Policy.IntermissionStopClockEnable = getPolicies.IntermissionStopClockEnable == 0 ? false : true;
                    game.Policy.IntermissionStopClockIncrementJamNumber = getPolicies.IntermissionStopClockIncrementJamNumber == 0 ? false : true;
                    game.Policy.IntermissionStopClockIncrementPeriodNumber = getPolicies.IntermissionStopClockIncrementPeriodNumber == 0 ? false : true;
                    game.Policy.IntermissionStopClockResetJamNumber = getPolicies.IntermissionStopClockResetJamNumber == 0 ? false : true;
                    game.Policy.IntermissionStopClockResetJamTime = getPolicies.IntermissionStopClockResetJamTime == 0 ? false : true;
                    game.Policy.IntermissionStopClockResetPeriodNumber = getPolicies.IntermissionStopClockResetPeriodNumber == 0 ? false : true;
                    game.Policy.IntermissionStopClockResetPeriodTime = getPolicies.IntermissionStopClockResetPeriodTime == 0 ? false : true;
                    game.Policy.JamClockControlsLineUpClock = getPolicies.JamClockControlsLineUpClock == 0 ? false : true;
                    game.Policy.JamClockControlsTeamPositions = getPolicies.JamClockControlsTeamPositions == 0 ? false : true;
                    game.Policy.JamClockTimePerJam = (long)getPolicies.JamClockTimePerJam;
                    game.Policy.LineupClockControlsStartJam = getPolicies.LineupClockControlsStartJam == 0 ? false : true;
                    game.Policy.LineUpClockPerJam = (long)getPolicies.LineUpClockPerJam;
                    game.Policy.NumberOfPeriods = (int)getPolicies.NumberOfPeriods;
                    game.Policy.PenaltyBoxControlsLeadJammer = getPolicies.PenaltyBoxControlsLeadJammer == 0 ? false : true;
                    game.Policy.PeriodClock = (long)getPolicies.PeriodClock;
                    game.Policy.PeriodClockControlsLineupJamClock = getPolicies.PeriodClockControlsLineupJamClock == 0 ? false : true;
                    game.Policy.SecondIntermissionNameConfirmedText = getPolicies.SecondIntermissionNameConfirmedText;
                    game.Policy.SecondIntermissionNameText = getPolicies.SecondIntermissionNameText;
                    game.Policy.TimeOutClock = (long)getPolicies.TimeOutClock;
                    game.Policy.TimeoutClockControlsLineupClock = getPolicies.TimeoutClockControlsLineupClock == 0 ? false : true;
                    game.Policy.TimeOutsPerPeriod = (int)getPolicies.TimeOutsPerPeriod;
                }




                //TODO: get game adverts.


                var getTimeOuts = getGame.GameTimeouts.ToList();
                foreach (var time in getTimeOuts)
                {
                    TimeOutViewModel tvm = new TimeOutViewModel();

                    tvm.TimeoutId = time.TimeOutId;
                    if (time.GameTeam != null && time.GameTeam.TeamId == game.Team1.TeamId)
                        tvm.TimeOutType = TimeOutTypeEnum.Team1;
                    else if (time.GameTeam != null && time.GameTeam.TeamId == game.Team2.TeamId)
                        tvm.TimeOutType = TimeOutTypeEnum.Team2;
                    else
                        tvm.TimeOutType = TimeOutTypeEnum.Offical;

                    if (game.TimeOuts == null)
                        game.TimeOuts = new List<TimeOutViewModel>();

                    game.TimeOuts.Add(tvm);
                }

                return game;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return null;
        }
        private static void insertNewPoliciesIntoDb(GameViewModel game, ManagementContext db)
        {
            try
            {
                var g = db.Games.Where(x => x.GameId == game.GameId).First();

                if (g.GamePolicy == null)
                    g.GamePolicy = new GamePolicy();
                g.GamePolicy.AdChangeAutomaticallyChangeImage = game.Policy.AdChangeAutomaticallyChangeImage ? 1 : 0;
                g.GamePolicy.AdChangeDisplayChangesInMilliSeconds = game.Policy.AdChangeDisplayChangesInMilliSeconds;
                g.GamePolicy.AdChangeShowAdsDuringIntermission = game.Policy.AdChangeShowAdsDuringIntermission ? 1 : 0;
                g.GamePolicy.AdChangeShowAdsRandomly = game.Policy.AdChangeShowAdsRandomly ? 1 : 0;
                g.GamePolicy.AdChangeUseLineUpClock = game.Policy.AdChangeUseLineUpClock ? 1 : 0;
                g.GamePolicy.AlwaysShowJamClock = game.Policy.AlwaysShowJamClock ? 1 : 0;
                g.GamePolicy.Created = DateTime.UtcNow;
                g.GamePolicy.EnableAdChange = game.Policy.EnableAdChange ? 1 : 0;
                g.GamePolicy.EnableIntermissionNaming = game.Policy.EnableIntermissionNaming ? 1 : 0;
                g.GamePolicy.EnableIntermissionStartOfClock = game.Policy.EnableIntermissionStartOfClock ? 1 : 0;
                g.GamePolicy.FirstIntermissionNameConfirmedText = game.Policy.FirstIntermissionNameConfirmedText;
                g.GamePolicy.FirstIntermissionNameText = game.Policy.FirstIntermissionNameText;
                g.GamePolicy.GameSelectionType = game.Policy.GameSelectionType.ToString();
                g.GamePolicy.HideClockTimeAfterBout = game.Policy.HideClockTimeAfterBout ? 1 : 0;
                g.GamePolicy.IntermissionOtherText = game.Policy.IntermissionOtherText;
                g.GamePolicy.IntermissionStartOfClockInMilliseconds = game.Policy.IntermissionStartOfClockInMilliseconds;
                g.GamePolicy.IntermissionStopClockEnable = game.Policy.IntermissionStopClockEnable ? 1 : 0;
                g.GamePolicy.OfficialTimeOutKeyShortcut = game.Policy.OfficialTimeOutKeyShortcut.ToString();
                g.GamePolicy.StartJamKeyShortcut = game.Policy.StartJamKeyShortcut.ToString();
                g.GamePolicy.StopJamKeyShortcut = game.Policy.StopJamKeyShortcut.ToString();
                g.GamePolicy.Team1LeadJammerKeyShortcut = game.Policy.Team1LeadJammerKeyShortcut.ToString();
                g.GamePolicy.Team1ScoreDownKeyShortcut = game.Policy.Team1ScoreDownKeyShortcut.ToString();
                g.GamePolicy.Team1ScoreUpKeyShortcut = game.Policy.Team1ScoreUpKeyShortcut.ToString();
                g.GamePolicy.Team1TimeOutKeyShortcut = game.Policy.Team1TimeOutKeyShortcut.ToString();
                g.GamePolicy.Team2LeadJammerKeyShortcut = game.Policy.Team2LeadJammerKeyShortcut.ToString();
                g.GamePolicy.Team2ScoreDownKeyShortcut = game.Policy.Team2ScoreDownKeyShortcut.ToString();
                g.GamePolicy.Team2ScoreUpKeyShortcut = game.Policy.Team2ScoreUpKeyShortcut.ToString();
                g.GamePolicy.Team2TimeOutKeyShortcut = game.Policy.Team2TimeOutKeyShortcut.ToString();
                g.GamePolicy.StopLineUpClockAtZero = game.Policy.StopLineUpClockAtZero ? 1 : 0;
                g.GamePolicy.StopPeriodClockWhenLineUpClockHitsZero = game.Policy.StopPeriodClockWhenLineUpClockHitsZero ? 1 : 0;
                db.SaveChanges();
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
        }
        /// <summary>
        /// inserts game links into the DB.
        /// </summary>
        /// <param name="game"></param>
        /// <param name="db"></param>
        /// <param name="gameNew"></param>
        private static void InsertGameLinks(GameViewModel game, ManagementContext db, DataModels.Game.Game gameNew)
        {
            if (game.GameLinks != null && game.GameLinks.Count > 0)
            {
                foreach (var link in game.GameLinks)
                {
                    var linkDb = db.GameLinks.Where(x => x.GameLinkId == link.LinkId).FirstOrDefault();

                    if (linkDb == null)
                    {
                        GameLink links = new GameLink();
                        links.Game = gameNew;
                        links.GameLinkId = link.LinkId;
                        links.Link = link.GameLink;
                        int type = Convert.ToInt32(link.LinkType);
                        links.LinkType = type;
                        db.GameLinks.Add(links);
                        db.SaveChanges();
                    }
                    else
                    {
                        linkDb.Link = link.GameLink;
                        int type = Convert.ToInt32(link.LinkType);
                        linkDb.LinkType = type;
                        db.SaveChanges();
                    }
                }
            }
            db.SaveChanges();
        }
        /// <summary>
        /// updates the team scores to the DB.
        /// </summary>
        /// <param name="team"></param>
        /// <param name="game"></param>
        /// <param name="cachedGame"></param>
        /// <param name="db"></param>
        public static int updateTeamScores(TeamNumberEnum team, Guid teamId, GameViewModel game, ManagementContext db, DataModels.Game.Game g)
        {
            try
            {
                List<ScoreViewModel> scoresNew = new List<ScoreViewModel>();

                if (team == TeamNumberEnum.Team1)
                    scoresNew = game.ScoresTeam1;
                else
                    scoresNew = game.ScoresTeam2;
                int scoreCount = 0;
                foreach (var score in scoresNew)
                {
                    var tdb = g.GameTeams.Where(x => x.TeamId == teamId).FirstOrDefault();
                    var scoredb = tdb.GameScores.Where(x => x.GameScoreId == score.PointId).FirstOrDefault();

                    if (scoredb == null)
                        GameScoreClass.insertScoreIntoDb(teamId, game, score, db, g);
                    else
                        scoredb.Point = score.Points;
                    scoreCount += score.Points;
                }
                db.SaveChanges();
                return scoreCount;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: "tried updating team scores");
            }
            return 0;
        }
        public static int updateJamToDb(GameViewModel game, ManagementContext db, JamViewModel jam, DataModels.Game.Game gDb)
        {
            int c = 0;
            try
            {


                var findJam = gDb.GameJams.Where(x => x.JamId == jam.JamId).FirstOrDefault();

                if (findJam == null)
                    GameJamClass.insertNewJamIntoDb(game.GameId, game.Team1.TeamId, game.Team2.TeamId, jam, db, gDb);
                else
                {
                    findJam.Game = findJam.Game;
                    findJam.CurrentPeriod = jam.CurrentPeriod;
                    findJam.DidJamEndWithInjury = jam.DidJamEndWithInjury;
                    findJam.DidJamGetCalledByJammerT1 = jam.DidJamGetCalledByJammerT1;
                    findJam.DidJamGetCalledByJammerT2 = jam.DidJamGetCalledByJammerT2;
                    findJam.TotalPointsForJamT1 = jam.TotalPointsForJamT1;
                    findJam.TotalPointsForJamT2 = jam.TotalPointsForJamT2;
                    findJam.GameTimeElapsedMillisecondsEnd = jam.GameTimeElapsedMillisecondsEnd;
                    findJam.GameTimeElapsedMillisecondsStart = jam.GameTimeElapsedMillisecondsStart;
                    c += db.SaveChanges();
                    try
                    {
                        for (int i = 0; i < jam.LeadJammers.Count; i++)
                        {
                            try
                            {
                                var j = findJam.LeadJammers.Where(x => x.GameJamLeadId == jam.LeadJammers[i].GameLeadJamId).FirstOrDefault();
                                if (j == null)
                                {
                                    GameLeadJammer l = new GameLeadJammer();
                                    l.GameJam = findJam;
                                    l.GameMemberId = jam.LeadJammers[i].Jammer.SkaterId;
                                    l.GameTimeInMilliseconds = jam.LeadJammers[i].GameTimeInMilliseconds;
                                    l.JamTimeInMilliseconds = jam.LeadJammers[i].JamTimeInMilliseconds;
                                    l.GameJamLeadId = jam.LeadJammers[i].GameLeadJamId;
                                    findJam.LeadJammers.Add(l);
                                }
                            }
                            catch (Exception exception)
                            {
                                ErrorDatabaseManager.AddException(exception, exception.GetType());
                            }
                        }
                        c += db.SaveChanges();
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                    try
                    {
                        for (int i = 0; i < jam.JamPasses.Count; i++)
                        {
                            try
                            {
                                var pass = findJam.JamPasses.Where(x => x.GamePassId == jam.JamPasses[i].PassId).FirstOrDefault();
                                if (pass == null)
                                {
                                    GameJamPasses p = new GameJamPasses();
                                    p.GameJam = findJam;
                                    p.GamePassId = jam.JamPasses[i].PassId;
                                    p.JamTimeMilliseconds = jam.JamPasses[i].JamTimeMilliseconds;
                                    p.PassNumber = jam.JamPasses[i].PassNumber;
                                    p.PointsScoredForPass = jam.JamPasses[i].PointsScoredForPass;
                                    p.SkaterWhoPassed = GameMemberClass.getMemberOfTeamInGame(jam.JamPasses[i].SkaterWhoPassed.SkaterId, gDb);
                                    p.TeamNumberEnum = (byte)jam.JamPasses[i].Team;
                                    findJam.JamPasses.Add(p);
                                }
                                else
                                {
                                    pass.PointsScoredForPass = jam.JamPasses[i].PointsScoredForPass;
                                }
                            }
                            catch (Exception exception)
                            {
                                ErrorDatabaseManager.AddException(exception, exception.GetType());
                            }
                        }
                        c += db.SaveChanges();
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, exception.GetType());
                    }
                    if ((jam.Blocker1T1 != null && findJam.Blocker1Team1 == null) || (jam.Blocker1T1 != null && findJam.Blocker1Team1.GameMemberId != jam.Blocker1T1.SkaterId))
                    {
                        var m = GameMemberClass.getMemberOfTeamInGame(game.Team1.TeamId, jam.Blocker1T1.SkaterId, gDb);
                        if (m != null)
                            findJam.Blocker1Team1 = m;
                    }
                    if ((jam.Blocker1T2 != null && findJam.Blocker1Team2 == null) || (jam.Blocker1T2 != null && findJam.Blocker1Team2.GameMemberId != jam.Blocker1T2.SkaterId))
                    {
                        var m = GameMemberClass.getMemberOfTeamInGame(game.Team2.TeamId, jam.Blocker1T2.SkaterId, gDb);
                        if (m != null)
                            findJam.Blocker1Team2 = m;
                    }
                    if ((jam.Blocker2T1 != null && findJam.Blocker2Team1 == null) || (jam.Blocker2T1 != null && findJam.Blocker2Team1.GameMemberId != jam.Blocker2T1.SkaterId))
                    {
                        var m = GameMemberClass.getMemberOfTeamInGame(game.Team1.TeamId, jam.Blocker2T1.SkaterId, gDb);
                        if (m != null)
                            findJam.Blocker2Team1 = m;
                    }
                    if ((jam.Blocker2T2 != null && findJam.Blocker2Team2 == null) || (jam.Blocker2T2 != null && findJam.Blocker2Team2.GameMemberId != jam.Blocker2T2.SkaterId))
                    {
                        var m = GameMemberClass.getMemberOfTeamInGame(game.Team2.TeamId, jam.Blocker2T2.SkaterId, gDb);
                        if (m != null)
                            findJam.Blocker2Team2 = m;
                    }
                    if ((jam.Blocker3T1 != null && findJam.Blocker3Team1 == null) || (jam.Blocker3T1 != null && findJam.Blocker3Team1.GameMemberId != jam.Blocker3T1.SkaterId))
                    {
                        var m = GameMemberClass.getMemberOfTeamInGame(game.Team1.TeamId, jam.Blocker3T1.SkaterId, gDb);
                        if (m != null)
                            findJam.Blocker3Team1 = m;
                    }
                    if ((jam.Blocker3T2 != null && findJam.Blocker3Team2 == null) || (jam.Blocker3T2 != null && findJam.Blocker3Team2.GameMemberId != jam.Blocker3T2.SkaterId))
                    {
                        var m = GameMemberClass.getMemberOfTeamInGame(game.Team2.TeamId, jam.Blocker3T2.SkaterId, gDb);
                        if (m != null)
                            findJam.Blocker3Team2 = m;
                    }
                    if ((jam.Blocker4T1 != null && findJam.Blocker4Team1 == null) || (jam.Blocker4T1 != null && findJam.Blocker4Team1.GameMemberId != jam.Blocker4T1.SkaterId))
                    {
                        var m = GameMemberClass.getMemberOfTeamInGame(game.Team1.TeamId, jam.Blocker4T1.SkaterId, gDb);
                        if (m != null)
                            findJam.Blocker4Team1 = m;
                    }
                    if ((jam.Blocker4T2 != null && findJam.Blocker4Team2 == null) || (jam.Blocker4T2 != null && findJam.Blocker4Team2.GameMemberId != jam.Blocker4T2.SkaterId))
                    {
                        var m = GameMemberClass.getMemberOfTeamInGame(game.Team2.TeamId, jam.Blocker4T2.SkaterId, gDb);
                        if (m != null)
                            findJam.Blocker4Team2 = m;
                    }
                    if ((jam.PivotT1 != null && findJam.PivotTeam1 == null) || (jam.PivotT1 != null && findJam.PivotTeam1.GameMemberId != jam.PivotT1.SkaterId))
                    {
                        var m = GameMemberClass.getMemberOfTeamInGame(game.Team1.TeamId, jam.PivotT1.SkaterId, gDb);
                        if (m != null)
                            findJam.PivotTeam1 = m;
                    }
                    if ((jam.PivotT2 != null && findJam.PivotTeam2 == null) || (jam.PivotT2 != null && findJam.PivotTeam2.GameMemberId != jam.PivotT2.SkaterId))
                    {
                        var m = GameMemberClass.getMemberOfTeamInGame(game.Team2.TeamId, jam.PivotT2.SkaterId, gDb);
                        if (m != null)
                            findJam.PivotTeam2 = m;
                    }
                    if ((jam.JammerT1 != null && findJam.JammerTeam1 == null) || (jam.JammerT1 != null && findJam.JammerTeam1.GameMemberId != jam.JammerT1.SkaterId))
                    {
                        var m = GameMemberClass.getMemberOfTeamInGame(game.Team1.TeamId, jam.JammerT1.SkaterId, gDb);
                        if (m != null)
                        {
                                                        findJam.JammerTeam1 = m;
                            findJam.DidTeam1JammerLoseLeadEligibility = jam.JammerT1.LostLeadJammerEligibility;
                        }
                    }
                    if ((jam.JammerT2 != null && findJam.JammerTeam2 == null) || (jam.JammerT2 != null && findJam.JammerTeam2.GameMemberId != jam.JammerT2.SkaterId))
                    {
                        var m = GameMemberClass.getMemberOfTeamInGame(game.Team2.TeamId, jam.JammerT2.SkaterId, gDb);
                        if (m != null)
                        {
                            findJam.JammerTeam2 = m;
                            findJam.DidTeam2JammerLoseLeadEligibility = jam.JammerT2.LostLeadJammerEligibility;
                        }
                    }

                    c += db.SaveChanges();
                }
                var findClock = (from xx in db.GameStopWatch
                                 where xx.StopwatchForId == game.GameId
                                 where xx.JamId == jam.JamId
                                 select xx).FirstOrDefault();
                if (findClock != null && jam.JamClock != null)
                {
                    findClock.IsClockAtZero = jam.JamClock.IsClockAtZero == true ? 1 : 0;
                    findClock.IsRunning = jam.JamClock.IsRunning == true ? 1 : 0;
                    findClock.Length = jam.JamClock.TimerLength;
                    if (jam.JamClock.StartTime != new DateTime())
                        findClock.StartDateTime = jam.JamClock.StartTime;
                    findClock.TimeElapsed = jam.JamClock.TimeElapsed;
                    findClock.TimeRemaining = jam.JamClock.TimeRemaining;
                    findClock.LastModified = DateTime.UtcNow;
                    findClock.Game = gDb;
                    db.SaveChanges();
                }
                else if (jam.JamClock != null && jam.JamClock.StartTime != new DateTime())
                {
                    GameStopwatch stop = new GameStopwatch();
                    stop.Created = DateTime.UtcNow;
                    stop.IsClockAtZero = jam.JamClock.IsClockAtZero == true ? 1 : 0;
                    stop.IsRunning = jam.JamClock.IsRunning == true ? 1 : 0;
                    stop.Length = jam.JamClock.TimerLength;
                    if (jam.JamClock.StartTime != new DateTime())
                        stop.StartDateTime = jam.JamClock.StartTime;
                    stop.StopwatchForId = game.GameId;
                    stop.TimeElapsed = jam.JamClock.TimeElapsed;
                    stop.TimeRemaining = jam.JamClock.TimeRemaining;
                    stop.JamNumber = jam.JamNumber;
                    stop.JamId = jam.JamId;
                    stop.Type = (int)StopWatchTypeEnum.JamClock;
                    stop.Game = gDb;
                    db.GameStopWatch.Add(stop);
                    db.SaveChanges();
                }
                c += db.SaveChanges();
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return c;
        }
        /// <summary>
        ///         /// entry point for saving a game to the DB.
        /// returns if the game is published online.
        /// </summary>
        /// <param name="game"></param>
        /// <returns>the fact the game was actually saved.</returns>
        public static DataModels.Game.Game saveGameToDb(GameViewModel game)
        {
            try
            {
                if (game != null)
                {
                    ManagementContext db = new ManagementContext();
                    var gameId = (from xx in db.Games
                                  where xx.GameId == game.GameId
                                  select xx).FirstOrDefault();
                    if (gameId == null)
                    {
                        var gameNew = insertNewGameToDb(game, db);
                        return gameNew;
                    }
                    else
                    {
                        deepCompareAndInsertDb(game, db, gameId);
                        return gameId;

                    }
                }
            }
            catch (Exception e)
            {
                Library.Classes.Error.ErrorDatabaseManager.AddException(e, e.GetType(), ErrorGroupEnum.Database);
            }
            return null;
        }
        private static DataModels.Game.Game insertNewGameToDb(GameViewModel game, ManagementContext db)
        {
            DataModels.Game.Game gameNew = new DataModels.Game.Game();
            gameNew.IdForOnlineManagementUse = game.IdForOnlineManagementUse;
            gameNew.GameDate = game.GameDate;
            gameNew.LastModified = DateTime.UtcNow;

            if (game.GameEndDate != DateTime.MinValue)
                gameNew.GameEndDate = game.GameEndDate;
            else
                gameNew.GameEndDate = game.GameDate;

            //debug or live mode.  Debug is for developing it, so users never see this mode and only open to developers.
            gameNew.ScoreboardType = Convert.ToInt32(game.ScoreboardMode);
            if (!String.IsNullOrEmpty(game.GameName))
                gameNew.GameName = game.GameName;
            else
                gameNew.GameName = ScoreboardConfig.DEFAULT_GAME_NAME;
            if (game.Policy != null)
                gameNew.GameType = game.Policy.GameSelectionType.ToString();
            gameNew.IsGameOver = game.HasGameEnded;
            gameNew.HasGameStarted = game.HasGameStarted;
            gameNew.IsGameLive = game.PublishGameOnline;
            gameNew.IsGameScrimmage = game.SaveGameOnline;
            gameNew.GameLocation = game.GameLocation;
            gameNew.GameCity = game.GameCity;
            gameNew.GameState = game.GameState;
            gameNew.GameId = game.GameId;
            gameNew.VersionNumber = game.VersionNumber;


            gameNew.IsGamePublishedOnline = game.PublishGameOnline;
            gameNew.Created = DateTime.UtcNow;
            if (game.FederationId != new Guid())
            {
                GameFederationOwnership fedOwner = new GameFederationOwnership();
                fedOwner.Federation = db.Federations.Where(x => x.FederationId == game.FederationId).FirstOrDefault();
                fedOwner.Game = gameNew;
                fedOwner.OwnerType = Convert.ToInt32(GameOwnerEnum.Owner);
                gameNew.FederationOwners.Add(fedOwner);
            }
            db.Games.Add(gameNew);
            int c = db.SaveChanges();

            InsertGameLinks(game, db, gameNew);

            //inserts the current jam into the DB.
            if (game.CurrentJam != null)
            {
                GameJamClass.insertNewJamIntoDb(game.GameId, game.Team1.TeamId, game.Team2.TeamId, game.CurrentJam, db, gameNew);
            }
            c += db.SaveChanges();

            if (game.CurrentLineUpClock != null && game.CurrentLineUpClock.StartTime != new DateTime())
            {
                GameStopwatch stop = new GameStopwatch();
                stop.Created = DateTime.UtcNow;
                stop.IsClockAtZero = game.CurrentLineUpClock.IsClockAtZero == true ? 1 : 0;
                stop.IsRunning = game.CurrentLineUpClock.IsRunning == true ? 1 : 0;
                stop.Length = game.CurrentLineUpClock.TimerLength;
                stop.StartDateTime = game.CurrentLineUpClock.StartTime;
                stop.StopwatchForId = game.GameId;
                stop.TimeElapsed = game.CurrentLineUpClock.TimeElapsed;
                stop.TimeRemaining = game.CurrentLineUpClock.TimeRemaining;
                stop.Type = (int)StopWatchTypeEnum.LineUpClock;
                stop.Game = gameNew;
                db.GameStopWatch.Add(stop);
                c += db.SaveChanges();
            }
            if (game.CurrentTimeOutClock != null && game.CurrentTimeOutClock.StartTime != new DateTime())
            {
                GameStopwatch stop = new GameStopwatch();
                stop.Created = DateTime.UtcNow;
                stop.IsClockAtZero = game.CurrentTimeOutClock.IsClockAtZero == true ? 1 : 0;
                stop.IsRunning = game.CurrentTimeOutClock.IsRunning == true ? 1 : 0;
                stop.Length = game.CurrentTimeOutClock.TimerLength;
                stop.StartDateTime = game.CurrentTimeOutClock.StartTime;
                stop.StopwatchForId = game.GameId;
                stop.TimeElapsed = game.CurrentTimeOutClock.TimeElapsed;
                stop.TimeRemaining = game.CurrentTimeOutClock.TimeRemaining;
                stop.Type = (int)StopWatchTypeEnum.TimeOutClock;
                stop.Game = gameNew;
                db.GameStopWatch.Add(stop);
                c += db.SaveChanges();
            }
            if (game.IntermissionClock != null && game.IntermissionClock.StartTime != new DateTime())
            {
                GameStopwatch stop = new GameStopwatch();
                stop.Created = DateTime.UtcNow;
                stop.IsClockAtZero = game.IntermissionClock.IsClockAtZero == true ? 1 : 0;
                stop.IsRunning = game.IntermissionClock.IsRunning == true ? 1 : 0;
                stop.Length = game.IntermissionClock.TimerLength;
                stop.StartDateTime = game.IntermissionClock.StartTime;
                stop.StopwatchForId = game.GameId;
                stop.TimeElapsed = game.IntermissionClock.TimeElapsed;
                stop.TimeRemaining = game.IntermissionClock.TimeRemaining;
                stop.Type = (int)StopWatchTypeEnum.IntermissionClock;
                stop.Game = gameNew;
                db.GameStopWatch.Add(stop);
                c += db.SaveChanges();
            }
            try
            {
                if (game.PeriodClock != null && game.PeriodClock.StartTime != new DateTime())
                {
                    GameStopwatch stop = new GameStopwatch();
                    stop.Created = DateTime.UtcNow;
                    stop.IsClockAtZero = game.PeriodClock.IsClockAtZero == true ? 1 : 0;
                    stop.IsRunning = game.PeriodClock.IsRunning == true ? 1 : 0;
                    stop.Length = game.PeriodClock.TimerLength;
                    stop.StartDateTime = game.PeriodClock.StartTime;
                    stop.StopwatchForId = game.GameId;
                    stop.TimeElapsed = game.PeriodClock.TimeElapsed;
                    stop.TimeRemaining = game.PeriodClock.TimeRemaining;
                    stop.Type = (int)StopWatchTypeEnum.PeriodClock;
                    stop.Game = gameNew;
                    db.GameStopWatch.Add(stop);
                    c += db.SaveChanges();
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            //teams need to be inserted first before the jams...
            GameTeamClass.insertTeamIntoDb(game, game.Team1, db, gameNew);

            GameTeamClass.insertTeamIntoDb(game, game.Team2, db, gameNew);

            foreach (var jam in game.Jams)
            {
                GameJamClass.insertNewJamIntoDb(game.GameId, game.Team1.TeamId, game.Team2.TeamId, jam, db, gameNew);
            }
            foreach (var advert in game.Advertisements)
            {
                //TODO: save adverts, but we need to upload these from the scoreboard.
            }
            foreach (var timeout in game.TimeOuts)
            {
                insertTimeoutsIntoDb(game, timeout, db, gameNew);
            }
            foreach (var score in game.ScoresTeam1)
            {
                GameScoreClass.insertScoreIntoDb(game.Team1.TeamId, game, score, db, gameNew);
            }
            foreach (var score in game.ScoresTeam2)
            {
                GameScoreClass.insertScoreIntoDb(game.Team2.TeamId, game, score, db, gameNew);
            }
            for (int i = 0; i < game.AssistsForTeam1.Count; i++)
            {
                GameAssistsClass.insertAssistIntoDb(game.Team1.TeamId, game, game.AssistsForTeam1[i], db, gameNew);
            }
            for (int i = 0; i < game.AssistsForTeam2.Count; i++)
            {
                GameAssistsClass.insertAssistIntoDb(game.Team2.TeamId, game, game.AssistsForTeam2[i], db, gameNew);
            }
            for (int i = 0; i < game.BlocksForTeam1.Count; i++)
            {
                GameBlocksClass.insertBlockIntoDb(game.Team1.TeamId, game, game.BlocksForTeam1[i], db, gameNew);
            }
            for (int i = 0; i < game.BlocksForTeam2.Count; i++)
            {
                GameBlocksClass.insertBlockIntoDb(game.Team2.TeamId, game, game.BlocksForTeam2[i], db, gameNew);
            }
            for (int i = 0; i < game.OfficialReviews.Count; i++)
            {
                OfficialReviewsClass.AddOfficialReview(game, gameNew, game.OfficialReviews[i]);
            }
            c += db.SaveChanges();
            //penalties added for the team.
            for (int i = 0; i < game.PenaltiesForTeam1.Count; i++)
            {
                GamePenaltiesClass.insertPenaltyIntoDb(game.Team1.TeamId, game, game.PenaltiesForTeam1[i], db, gameNew);
            }
            for (int i = 0; i < game.PenaltiesForTeam2.Count; i++)
            {
                GamePenaltiesClass.insertPenaltyIntoDb(game.Team2.TeamId, game, game.PenaltiesForTeam2[i], db, gameNew);
            }
            //times the skater went to the box.
            foreach (var pen in game.PenaltyBox)
            {
                GamePenaltiesClass.insertNewPenaltyIntoDb(game, db, pen, gameNew);
            }
            if (game.Policy != null)
            {
                insertNewPoliciesIntoDb(game, db);
            }
            if (game.Officials != null)
            {
                GameOfficialsClass.AddOfficialsToDb(game, db, gameNew);
            }

            c += db.SaveChanges();
            return gameNew;
        }
 public static void addGameToBeingAddedList(GameViewModel game)
 {
     GameCache.saveGameToGamesGettingAddedCache(game);
 }
 /// <summary>
 /// gets the current period clock for the game.
 /// </summary>
 /// <param name="id"></param>
 /// <param name="game"></param>
 /// <returns></returns>
 public  static GameStopwatch getPeriodClock(Guid id, GameViewModel game)
 {
     ManagementContext db = new ManagementContext();
     var getPeriod = (from xx in db.GameStopWatch
                      where xx.StopwatchForId == id
                      where xx.Type == (int)StopWatchTypeEnum.PeriodClock
                      select xx).FirstOrDefault();
     if (getPeriod != null)
     {
         game.PeriodClock = new StopwatchWrapper();
         game.PeriodClock.IsClockAtZero = getPeriod.IsClockAtZero == 1 ? true : false;
         game.PeriodClock.IsRunning = getPeriod.IsRunning == 1 ? true : false;
         game.PeriodClock.StartTime = getPeriod.StartDateTime;
         game.PeriodClock.TimeElapsed = getPeriod.TimeElapsed;
         game.PeriodClock.TimeRemaining = getPeriod.TimeRemaining;
         game.PeriodClock.TimerLength = getPeriod.Length;
     }
     return getPeriod;
 }
        public static void insertPenaltyIntoDb(Guid teamId, GameViewModel game, PenaltyViewModel penalty, ManagementContext db, DataModels.Game.Game g)
        {
            try
            {
                GameMemberPenalty blocks = new GameMemberPenalty();
                blocks.DateTimePenaltied = penalty.CurrentDateTimePenalty;
                blocks.GamePenaltyId = penalty.PenaltyId;
                blocks.JamNumber = penalty.JamNumber;
                blocks.JamId = penalty.JamId;
                blocks.PeriodNumber = penalty.Period;
                blocks.PeriodTimeRemainingMilliseconds = penalty.GameTimeInMilliseconds;
                blocks.PenaltyType = Convert.ToInt32(penalty.PenaltyType);
                blocks.PenaltyScale = Convert.ToInt32(penalty.PenaltyScale);
                blocks.Game = g;
                blocks.MemberWhoPenaltied = g.GameTeams.Where(x => x.TeamId == teamId).FirstOrDefault().GameMembers.Where(x => x.GameMemberId == penalty.PenaltyAgainstMember.SkaterId).FirstOrDefault();
                if (blocks.MemberWhoPenaltied != null)
                {
                    db.GameMemberPenalty.Add(blocks);
                    db.SaveChanges();
                }

            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
        }
        /// <summary>
        /// loads the entire game to XML
        /// </summary>
        public void loadGameFromXml(string fileName)
        {
            try
            {
                XmlSerializer xs = new XmlSerializer(typeof(GameViewModel));
                if (File.Exists(Path.Combine(ScoreboardConfig.SAVE_GAMES_FILE_LOCATION, fileName)))
                {
                    StreamReader objReader = new StreamReader(Path.Combine(ScoreboardConfig.SAVE_GAMES_FILE_LOCATION, fileName));
                    GameViewModel game = (GameViewModel)xs.Deserialize(objReader);
                    instance = game;
                    setupTimerForOnlineGame();

                    //sets the timers on both the period clock and the jam clock
                    if (game.PeriodClock.StartTime == new DateTime())
                        instance.PeriodClock = new StopwatchWrapper(game.PeriodClock.TimerLength);
                    else
                        instance.PeriodClock = new StopwatchWrapper(game.PeriodClock.TimeRemaining);

                    if (instance.CurrentJam != null && instance.CurrentJam.JamClock != null)
                    {
                        if (game.CurrentJam.JamClock.StartTime == new DateTime())
                            instance.CurrentJam.JamClock = new StopwatchWrapper(game.CurrentJam.JamClock.TimerLength);
                        else
                            instance.CurrentJam.JamClock = new StopwatchWrapper(game.CurrentJam.JamClock.TimeRemaining);
                    }
                    instance.PeriodClock.PropertyChanged += new PropertyChangedEventHandler(PeriodClock_PropertyChanged);

                    foreach (var member in Instance.Team1.TeamMembers)
                        LoadPictureOfMemberFromSavedGame(member);

                    foreach (var member in Instance.Team2.TeamMembers)
                        LoadPictureOfMemberFromSavedGame(member);

                    foreach (var member in Instance.Officials.Nsos)
                        LoadPictureOfMemberFromSavedGame(member);
                    foreach (var member in Instance.Officials.Referees)
                        LoadPictureOfMemberFromSavedGame(member);

                    foreach (var member in Instance.Advertisements)
                    {
                        LoadPictureOAdvertismentFromSavedGame(member.FileLocation, member.AdvertGameId, member.AdvertismentPictureCompressed);
                        member.AdvertismentPictureCompressed = null;
                    }

                    if (GameViewModel.Instance.ScoreboardSettings != null)
                        LoadScoreboardBackground(fileName);

                    AdvertisementViewModel.getAdvertsFromDirectory();
                    SlideShowViewModel.getSlidesFromDirectory();

                    setupTimerForSlideShow();
                    setupAdvertisements();

                    PolicyViewModel.Instance.SetPolicy(instance.Policy);

                    PolicyViewModel.Instance.LoadBuzzerFromCompression();

                    instance.IsCurrentlySendingOnlineGame = false;
                    ///sends the first initial game to the server.
                    if (instance.PublishGameOnline || instance.SaveGameOnline)
                    {
                        sendLiveGameToServer();
                    }
                }
            }
            catch (Exception e)
            {
                ErrorViewModel.Save(e, this.GetType(), ErrorGroupEnum.UI);
            }
        }
        /// <summary>
        /// creates a new instance and overall a brand new roller derby game.
        /// </summary>
        public void createNewGame(GameTypeEnum gameType)
        {
            try
            {
                //we need to save the settings from the initial window that the user selected.
                bool saveGameOnline = GameViewModel.Instance.SaveGameOnline;
                bool publishGame = GameViewModel.Instance.PublishGameOnline;
                bool beingTested = GameViewModel.Instance.IsBeingTested;

                instance = new GameViewModel();
#if DEBUG
                instance.ScoreboardMode = ScoreboardModeEnum.Debug;
#else
                instance.ScoreboardMode = ScoreboardModeEnum.Live;
#endif
                instance.SaveGameOnline = saveGameOnline;
                instance.PublishGameOnline = publishGame;
                instance.IsBeingTested = beingTested;

                instance.GameId = Guid.NewGuid();
                instance.IdForOnlineManagementUse = Guid.NewGuid();

                instance.Policy = PolicyViewModel.Instance;
                instance.Team1.TimeOutsLeft = PolicyViewModel.Instance.TimeOutsPerPeriod;
                instance.Team2.TimeOutsLeft = PolicyViewModel.Instance.TimeOutsPerPeriod;
                //must start with a negative one for pre game intermissions...
                //should prob do this a better way, but havent figured it out yet.
                GameViewModel.Instance.CurrentPeriod = 0;

                //TODO: Team names should be different?
                instance.Team1.TeamName = "Home";
                instance.CurrentTeam1Score = 0;
                instance.CurrentTeam1JamScore = 0;
                instance.ScoresTeam1 = new List<ScoreViewModel>();
                instance.Team1.TeamId = Guid.NewGuid();
                instance.Team2.TeamName = "Away";

                instance.Team1.Logo = new TeamLogo();
                instance.Team2.Logo = new TeamLogo();
                instance.CurrentTeam2Score = 0;
                instance.CurrentTeam2JamScore = 0;
                instance.ScoresTeam2 = new List<ScoreViewModel>();
                instance.Team2.TeamId = Guid.NewGuid();
                instance.GameDate = DateTime.UtcNow;
                instance.TimeOuts = new List<TimeOutViewModel>();
                instance.GameName = "Bout";
                instance.CurrentIntermission = GameViewModelIntermissionTypeEnum.PreGameIntermission;
                instance.NameOfIntermission = PolicyViewModel.Instance.IntermissionOtherText;
                createNewPeriod();
                createLineUpClock();
                instance.Jams.Clear();
                instance.CurrentJam = null;
                createNewJam();
                createNewIntermission();
                instance.Advertisements = new List<AdvertisementViewModel>();
                instance.SlideShowSlides = new List<SlideShowViewModel>();
                AdvertisementViewModel.getAdvertsFromDirectory();
                setupAdvertisements();
                setCurrentAdvertisement();
                _team1.clearTeamPositions();
                _team2.clearTeamPositions();
                setupTimerForOnlineGame();
                setupTimerForSlideShow();
                instance.EditModeItems = new List<EditModeModel>();
                instance.AssistsForTeam1 = new List<AssistViewModel>();
                instance.BlocksForTeam1 = new List<BlockViewModel>();
                instance.PenaltiesForTeam1 = new List<PenaltyViewModel>();
                instance.AssistsForTeam2 = new List<AssistViewModel>();
                instance.BlocksForTeam2 = new List<BlockViewModel>();
                instance.PenaltiesForTeam2 = new List<PenaltyViewModel>();
                instance.OfficialReviews = new List<OfficialReviewViewModel>();
                instance.UsingServerScoring = false;
                instance.Officials = new Officials.Officials();
                instance.ScoreboardSettings = new ScoreboardSettings();
                liveGameTimer_Elapsed(this, null);
                this.NewGame(this, null);
            }
            catch (Exception e)
            {
                ErrorViewModel.Save(e, this.GetType(), ErrorGroupEnum.UI);
            }
        }
 private static void insertTimeoutsIntoDb(GameViewModel game, TimeOutViewModel timeOuts, ManagementContext db, DataModels.Game.Game g)
 {
     try
     {
         GameTimeout time = new GameTimeout();
         time.Game = g;
         if (timeOuts.TimeOutType == TimeOutTypeEnum.Team1)
             time.GameTeam = g.GameTeams.Where(x => x.TeamId == game.Team1.TeamId).First();
         else if (timeOuts.TimeOutType == TimeOutTypeEnum.Team2)
             time.GameTeam = g.GameTeams.Where(x => x.TeamId == game.Team2.TeamId).First();
         time.TimeOutTime = timeOuts.TimeOutClock.TimeRemaining;
         time.TimeOutId = timeOuts.TimeoutId;
         db.GameTimeOut.Add(time);
         db.SaveChanges();
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
 }
        public static GameViewModel saveGameToDebuggingGamesCache(GameViewModel game)
        {
            try
            {
                var cache = GetCache(HttpContext.Current.Cache);
                var cachedGame = cache.CurrentLiveDebuggingGames.Where(x => x.GameId == game.GameId).FirstOrDefault();

                if (cachedGame != null)
                    cache.CurrentLiveDebuggingGames.Remove(cachedGame);

                cache.CurrentLiveDebuggingGames.Add(game);
                UpdateCache(cache);
                return game;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return null;
        }