public ActionResult Update(int tournamentId)
        {
            if (account.IsLoggedIn())
            {
                Models.Tournament tourny = new Models.Tournament(service, tournamentId);
                if (tourny.IsAdmin(account.Model.AccountID))
                {
                    ViewBag.Create     = false;
                    ViewBag.CanEdit    = tourny.CanEdit();
                    ViewBag.InProgress = tourny.Model.InProgress;
                    tourny.SetFields();
                    return(View("Create", tourny.viewModel));
                }
                else
                {
                    Session["Message"]       = "You do not have permission to do that.";
                    Session["Message.Class"] = ViewError.ERROR;

                    return(RedirectToAction("Tournament", "Tournament", new { guid = tourny.Model.TournamentID }));
                }
            }
            else
            {
                Session["Message"]       = "You need to login to do that";
                Session["Message.Class"] = ViewError.ERROR;

                return(RedirectToAction("Login", "Account"));
            }
        }
        public JsonResult CheckIn(int tournamentId, int tournamentUserId = -1)
        {
            Models.Tournament tournament = new Models.Tournament(service, tournamentId);


            if (tournament.IsAdmin(account.Model.AccountID))
            {
                // Check if a userId was provided first before checking an account
                if (tournamentUserId != -1)
                {
                    // An admin is checking in a user
                    status  = tournament.CheckUserIn(tournamentUserId);
                    message = "User is " + (status ? "" : "not") + " checked in";
                }
                else if (account.IsLoggedIn())
                {
                    // A user with an account is checking in.
                    status  = tournament.CheckAccountIn(account.Model.AccountID);
                    message = "Account is " + (status ? "" : "not") + " checked in";
                }
            }
            else
            {
                message = "You can not do this.";
            }

            data = new
            {
                isCheckedIn = tournament.isUserCheckedIn(tournamentUserId),
                targetUser  = tournamentUserId
            };
            return(BundleJson());
        }
        public JsonResult Finalize(int tournamentId, int bracketId, Dictionary <String, Dictionary <String, int> > roundData)
        {
            String redirect = Url.Action("Tournament", "Tournament", new { guid = tournamentId });

            if (account.IsLoggedIn())
            {
                // Load the tournament
                Models.Tournament tournament = new Models.Tournament(service, tournamentId);
                if (tournament.IsAdmin(account.Model.AccountID))
                {
                    if (tournament.FinalizeBracket(bracketId, roundData))
                    {
                        status  = true;
                        message = "Your tournament has been finalized. No changes can be made.";

                        Session["Message"]       = message;
                        Session["Message.Class"] = ViewError.SUCCESS;
                    }
                    else
                    {
                        message = "An error occurred while trying to create the matches.";

                        Session["Message"]       = message;
                        Session["Message.Class"] = ViewError.ERROR;
                    }
                }
                else
                {
                    message = "You are not allowed to do that.";

                    Session["Message"]       = message;
                    Session["Message.Class"] = ViewError.ERROR;
                }
            }
            else
            {
                message  = "You must login to do that.";
                redirect = Url.Action("Login", "Account");

                Session["Message"]       = message;
                Session["Message.Class"] = ViewError.ERROR;
            }

            data = new { redirect = redirect };


            return(BundleJson());
        }
        public ActionResult Update(TournamentViewModel viewModel, int tournamentId)
        {
            if (account.IsLoggedIn())
            {
                Models.Tournament tourny = new Models.Tournament(service, tournamentId);

                if (tourny.IsAdmin(account.Model.AccountID))
                {
                    if (tourny.Update(viewModel, account.Model.AccountID))
                    {
                        Session["Message"]       = "Edits to the tournament was successful";
                        Session["Message.Class"] = ViewError.SUCCESS;

                        return(RedirectToAction("Tournament", "Tournament", new { guid = tourny.Model.TournamentID }));
                    }
                    else
                    {
                        Session["Message"]       = "We were unable to update your tournament.";
                        Session["Message.Class"] = ViewError.ERROR;
                    }
                }
                else
                {
                    Session["Message"]       = "You do not have permission to update this tournament";
                    Session["Message.Class"] = ViewError.ERROR;
                }

                ViewBag.Create     = false;
                ViewBag.CanEdit    = tourny.CanEdit();
                ViewBag.InProgress = tourny.Model.InProgress;

                return(View("Create", viewModel));
            }
            else
            {
                Session["Message"]       = "You must login to edit a tournament.";
                Session["Message.Class"] = ViewError.ERROR;
                return(RedirectToAction("Login", "Account"));
            }
        }
        public JsonResult NoAccountRegister(int tournamentId, String name, int bracketId)
        {
            if (account.IsLoggedIn())
            {
                Models.Tournament tournament = new Models.Tournament(service, tournamentId);

                // Is an Administrator registering a user?
                if (tournament.IsAdmin(account.Model.AccountID))
                {
                    TournamentUserModel model = tournament.AddUser(name);
                    data = new
                    {
                        user = new
                        {
                            Name             = model.Name,
                            Permission       = model.PermissionLevel,
                            TournamentUserId = model.TournamentUserID,
                            Seed             = tournament.GetUserSeed(bracketId, model.TournamentUserID)
                        },
                        actions = tournament.PermissionAction(account.Model.AccountID, model.TournamentUserID, "default")
                    };
                    if (data != null)
                    {
                        status = true;
                    }
                    message = "User was " + (status ? "" : "not") + " added successfully";
                }
                else
                {
                    message = "You are not allowed to register a user.";
                }
            }
            else
            {
                message = "You need to login first.";
            }

            return(BundleJson());
        }
        public JsonResult Lockout(int tournamentId, int bracketId)
        {
            if (account.IsLoggedIn())
            {
                Models.Tournament tournament = new Models.Tournament(service, tournamentId);

                if (tournament.IsAdmin(account.Model.AccountID))
                {
                    status = tournament.LockBracket(bracketId, true);

                    if (status)
                    {
                        message = "Bracket is not locked.";
                    }
                    else
                    {
                        message = "Bracket failed to lock.";
                    }
                }
            }
            return(BundleJson());
        }
        public JsonResult Reset(int tournamentId, int bracketId, int matchNum)
        {
            if (account.IsLoggedIn())
            {
                Models.Tournament tournament = new Models.Tournament(service, tournamentId);
                Models.Bracket    bracket    = tournament.GetBracket(bracketId);

                if (tournament.IsAdmin(account.Model.AccountID))
                {
                    List <int>    matchNumsAffected = bracket.MatchesAffectedList(matchNum);
                    List <object> matchResponse     = new List <object>();

                    bracket.IBracket.ResetMatchScore(matchNum);

                    foreach (int match in matchNumsAffected)
                    {
                        matchResponse.Add(JsonMatchResponse(bracket.GetMatchByNum(match), true));
                    }

                    status  = true;
                    message = "Matches are reset";
                    data    = new
                    {
                        isLocked = bracket.IsLocked,
                        matches  = matchResponse
                    };
                }
                else
                {
                    message = "You do not have permission to do this";
                }
            }
            else
            {
                message = "You must login to do this";
            }

            return(BundleJson());
        }
        public JsonResult RemoveGame(int tournamentId, int bracketId, int matchNum, int gameNum)
        {
            if (account.IsLoggedIn())
            {
                Models.Tournament tournament = new Models.Tournament(service, tournamentId);
                Models.Bracket    bracket    = tournament.GetBracket(bracketId);

                if (tournament.IsAdmin(account.Model.AccountID))
                {
                    //Models.Match match = bracket.GetMatchByNum(matchNum);
                    List <int>    matchesAffected     = bracket.MatchesAffectedList(matchNum);
                    List <object> matchesAffectedData = new List <object>();

                    if (bracket.RemoveGame(matchNum, gameNum))
                    {
                        foreach (int matchNumber in matchesAffected)
                        {
                            matchesAffectedData.Add(JsonMatchResponse(bracket.GetMatchByNum(matchNumber), true));
                        }

                        status  = true;
                        message = "Matches were updated";
                        data    = new
                        {
                            bracketFinished = bracket.IBracket.IsFinished,
                            isLocked        = bracket.IsLocked,
                            matches         = matchesAffectedData,
                        };
                    }
                    else
                    {
                        message = "There was an error in deleting the game";
                    }
                }
            }

            return(BundleJson());
        }
        public JsonResult SeedChange(int tournamentId, int bracketId, Dictionary <String, int> players)
        {
            if (account.IsLoggedIn())
            {
                Models.Tournament tournament = new Models.Tournament(service, tournamentId);

                if (tournament.IsAdmin(account.Model.AccountID))
                {
                    tournament.UpdateSeeds(players, bracketId);
                    status  = true;
                    message = "Seeds are updated";
                }
                else
                {
                    message = "An error occured. Please try again later";
                }
            }
            else
            {
                message = "You must login first";
            }

            return(BundleJson());
        }
        public JsonResult MatchUpdate(int tournamentId, int bracketId, int matchNum, List <GameViewModel> games)
        {
            if (games != null)
            {
                if (account.IsLoggedIn())
                {
                    Models.Tournament tournament = new Models.Tournament(service, tournamentId);
                    Models.Bracket    bracket    = tournament.GetBracket(bracketId);
                    Models.Match      match      = bracket.GetMatchByNum(matchNum);
                    bool validUpdate             = true;

                    if (tournament.IsAdmin(account.Model.AccountID))
                    {
                        // Verify these matches exists
                        foreach (GameViewModel gameModel in games)
                        {
                            PlayerSlot winner       = gameModel.DefenderScore > gameModel.ChallengerScore ? PlayerSlot.Defender : PlayerSlot.Challenger;
                            bool       containsGame = match.match.Games.Any(x => x.GameNumber == gameModel.GameNumber);

                            // Tie game check
                            if (gameModel.ChallengerScore == gameModel.DefenderScore)
                            {
                                continue;
                            }

                            // Add the game
                            if (!match.match.IsFinished && !containsGame)
                            {
                                if (!bracket.AddGame(matchNum, gameModel.DefenderScore, gameModel.ChallengerScore, winner))
                                {
                                    validUpdate = false;
                                    break;
                                }
                            }
                            // Update the game
                            else if (containsGame)
                            {
                                if (!bracket.UpdateGame(matchNum, gameModel.GameNumber, gameModel.DefenderScore, gameModel.ChallengerScore, winner))
                                {
                                    validUpdate = false;
                                    break;
                                }
                            }
                        }

                        // Updating of the matches happens by an event.
                        status = bracket.UpdateMatch(bracket.IBracket.GetMatchModel(matchNum));
                        match  = bracket.GetMatchByNum(matchNum);
                        bool refresh = bracket.roundsModified;

                        List <int>    matchesAffected = bracket.MatchesAffectedList(matchNum);
                        List <object> matchUpdates    = new List <object>();

                        if (status)
                        {
                            message = "Current match was updated";

                            // Creates objects for all matches affected, including the match you're currently on
                            foreach (int matchNumAffected in matchesAffected)
                            {
                                matchUpdates.Add(JsonMatchResponse(bracket.GetMatchByNum(matchNumAffected), false));
                            }
                        }

                        // Prepare data
                        data = new
                        {
                            bracketFinished = bracket.IBracket.IsFinished,
                            isLocked        = bracket.IsLocked,
                            matches         = matchUpdates,
                            refresh         = refresh
                        };
                    }
                    else
                    {
                        message = "You are not authorized to do this.";
                    }
                }
                else
                {
                    message = "You must login to do this action.";
                }
            }
            else
            {
                message = "No games were received.";
            }

            return(BundleJson());
        }
        public ActionResult Tournament(String guid, String inviteCode)
        {
            int tournamentId = ConvertToInt(guid);

            Models.Tournament tourny = new Models.Tournament(service, tournamentId);

            if (tournamentId == 0)
            {
                Session["Message"]       = "This tournament is invalid.";
                Session["Message.Class"] = ViewError.ERROR;
                return(RedirectToAction("Index", "Tournament"));
            }

            if (tourny.Model != null)
            {
                bool isAdmin       = tourny.IsAdmin(account.Model.AccountID);
                bool isParticipant = tourny.IsParticipent(account.Model.AccountID);

                // Should we check for registrations or view the tournament?
                if (!tourny.Model.InProgress && !isAdmin)
                {
                    // Verify if the user has an invite code or the invite code is valid
                    if (tourny.Model.PublicRegistration || tourny.Model.InviteCode == inviteCode)
                    {
                        TournamentRegisterViewModel fields = new TournamentRegisterViewModel()
                        {
                            AccountID    = account.Model.AccountID,
                            TournamentID = tourny.Model.TournamentID
                        };

                        // Allow the tournament registration to be shown
                        ViewBag.Tournament   = tourny.Model;
                        ViewBag.isRegistered = tourny.isRegistered(account.Model.AccountID);
                        ViewBag.CanRegister  = tourny.CanRegister();


                        return(View("RegisterForm", fields));
                    }
                    else
                    {
                        Session["Message"]       = "This tournament is not accepting registrations.";
                        Session["Message.Class"] = ViewError.WARNING;
                    }
                }
                else
                {
                    // Verify if the user is allowed to view the tournament
                    if (tourny.Model.PublicViewing || tourny.Model.InviteCode == inviteCode || isAdmin || isParticipant)
                    {
                        return(View("Tournament", tourny));
                    }
                    else
                    {
                        Session["Message"]       = "This tournament is not available to view.";
                        Session["Message.Class"] = ViewError.WARNING;
                    }
                }
            }
            else
            {
                Session["Message"]       = "The tournament you're looking for doesn't exist or is not publicly shared.";
                Session["Message.Class"] = ViewError.WARNING;
            }


            return(RedirectToAction("Search", "Tournament"));
        }