public ActionResult PositionCompetitionPlayers(int competitionId, CompetitionSection section)
        {
            var competitionManager = ServiceProvider.Get <ICompetitionsManager>();

            competitionManager.PositionCompetitionPlayers(competitionId, section);
            return(RedirectToAction("Details", new { id = competitionId }));
        }
Example #2
0
        public void PositionCompetitionPlayers(int id, CompetitionSection section)
        {
            var repository  = ServiceProvider.Get <ICompetitionRepository>();
            var competition = repository.GetCompetitionDetails(id);

            if (competition.IsNull())
            {
                throw new ArgumentException("Competition '{0}' does not exist.".ParseTemplate(id));
            }

            if ((int)competition.Status > (int)CompetitionStatus.Started)
            {
                throw new ArgumentException("Invalid status transition from '{1}' to Positioned, Competition Id: {0}.".ParseTemplate(id, competition.Status));
            }

            var competitionsEngine = ServiceProvider.Get <ICompetitionsEngine>();
            var matchesCreated     = false;

            if (competition.Matches.Length == 0)
            {
                competitionsEngine.CreateCompetitionsMatches(new[] { competition });
                matchesCreated = true;
            }

            competitionsEngine.UpdatePlayersPosition(id, section);
            if (matchesCreated)
            {
                competition = repository.GetCompetitionDetails(id);
            }

            competitionsEngine.QualifyByeMatches(competition, section);
        }
Example #3
0
        public void QualifyByeMatches(CompetitionDetails details, CompetitionSection section)
        {
            var competitionMatchesRepository = ServiceProvider.Get <ICompetitionMatchesRepository>();
            var sectionMatches = details.Matches.Where(m => m.Section == section && (m.Player1Code == BYE || m.Player2Code == BYE)).Select(m => competitionMatchesRepository.GetMatch(m.Id)).ToArray();

            foreach (var match in sectionMatches)
            {
                match.Result = MatchResult.Win;
                if (match.Player1Code == BYE)
                {
                    match.Winner = MatchWinner.Player2;
                }
                else if (match.Player2Code == BYE)
                {
                    match.Winner = MatchWinner.Player1;
                }


                UpdateMatchResult(new MatchScoreUpdateInfo()
                {
                    MatchId = match.Id, Result = match.Result, Winner = match.Winner
                });
                Qualify(match);
            }
        }
        public ActionResult Create(int? competitionId, int? replacePlayerId, string idNumber, CompetitionPlayerSource? source, CompetitionSection? section, CompetitionPlayerStatus? status, string reason)
        {
            var player = new Player();
            var model = new CreatePlayerModel { Player = player };

            if (competitionId.HasValue)
            {
                var competitionRepository = ServiceProvider.Get<ICompetitionRepository>();
                model.Competition = competitionRepository.GetCompetition(competitionId.Value);
                model.Source = source.GetValueOrDefault(CompetitionPlayerSource.Regular);
                model.Section = section.GetValueOrDefault(CompetitionSection.Final);
                model.Status = status.GetValueOrDefault(CompetitionPlayerStatus.Active);
                model.Reason = reason;

                if (replacePlayerId.HasValue)
                {
                    var playersRepository = ServiceProvider.Get<IPlayersRepository>();
                    model.ReplacedPlayer = playersRepository.Get(replacePlayerId.Value);
                }
            }

            if (idNumber.NotNullOrEmpty())
            {
                model.Player.IdNumber = idNumber;
            }
            return View(model);
        }
        private IEnumerable <MatchHeaderInfo> CreateSectionMatches(int playersCount, CompetitionSection section, int?qualifyingToNextSection = default(int?))
        {
            var actualPlayersCount = playersCount - qualifyingToNextSection.GetValueOrDefault();
            var rounds             = (int)Math.Log((playersCount), 2);
            var actualRounds       = rounds - (qualifyingToNextSection.GetValueOrDefault() > 0 ? (int)Math.Log(qualifyingToNextSection.GetValueOrDefault(), 2) : 0);
            var matches            = new List <MatchHeaderInfo>(playersCount);

            for (int i = 0; i < actualPlayersCount; i++)
            {
                var match = new MatchHeaderInfo();
                match.Section  = section;
                match.Position = i;
                match.Round    = rounds - Math.Max(0, (int)Math.Log((playersCount - (i + 1)), 2));
                match.IsFinal  = (match.Round == actualRounds);// && ((actualRounds == 1) || (i < playersCount - 1));
                if (section == CompetitionSection.Final && match.Round == rounds - 1)
                {
                    match.IsSemiFinal = true;
                }
                match.Status = MatchStatus.Created;
                matches.Add(match);
            }
            var matchesByRound = matches.GroupBy(m => m.Round).ToArray();

            foreach (var roundMatches in matchesByRound)
            {
                var index = 0;
                foreach (var match in roundMatches)
                {
                    match.RoundRelativePosition = index++;
                }
            }
            return(matches);
        }
Example #6
0
        public void UpdatePlayersPosition(int competitionId, CompetitionSection section)
        {
            var competitionDetails = GetCompetitionDetails(competitionId);

            var positioningEngine = GetPositioningEngine(competitionDetails.Type.Method);

            var positions = positioningEngine.PositionPlayers(competitionDetails, section);

            var competitionMatchesRepository = ServiceProvider.Get <ICompetitionMatchesRepository>();

            competitionMatchesRepository.UpdatePlayersPosition(competitionId, positions);
        }
Example #7
0
        public MatchHeaderInfo GetMatchByPosition(int competitionId, CompetitionSection section, int position)
        {
            var result = default(MatchHeaderInfo);

            UseDataContext(
                dataContext =>
            {
                var match = dataContext.Matches.FirstOrDefault(m => m.CompetitionId == competitionId && m.SectionId == (int)section && m.Position == position);

                result = match.MapFromData();
            });
            return(result);
        }
Example #8
0
        public int GetCompetitionSectionRounds(int competitionId, CompetitionSection section)
        {
            var rounds = 6;

            UseDataContext(
                dataContext =>
            {
                var minRound = dataContext.Matches.Where(m => m.CompetitionId == competitionId && m.SectionId == (int)section).Min(m => m.Round);
                rounds       = 6 - minRound;
            });

            return(rounds);
        }
        public ActionResult Print(int id, CompetitionSection section = CompetitionSection.Final)
        {
            var competitionEngine = ServiceProvider.Get<ICompetitionsEngine>();

            var competition = competitionEngine.GetCompetitionDetails(id);
            var gen = new CompetitionDrawGenerator(Path.GetTempPath());
            var outputPath = gen.Generate(competition, section);
            //var generator = new TournamentBracketGenerator();
            //var result = generator.Generate(competition, section);

            return View(new PrintModel { Path = outputPath });// Content(result);

        }
Example #10
0
        public int GetRoundMatchesCount(int competitionId, CompetitionSection section, int round)
        {
            var result = 0;

            UseDataContext(
                dataContext =>
            {
                result =
                    dataContext.Matches.Count(
                        m =>
                        m.CompetitionId == competitionId && m.SectionId == (int)section && m.Round == round);
            });
            return(result);
        }
        public ActionResult Print(int id, CompetitionSection section = CompetitionSection.Final)
        {
            var competitionEngine = ServiceProvider.Get <ICompetitionsEngine>();

            var competition = competitionEngine.GetCompetitionDetails(id);
            var gen         = new CompetitionDrawGenerator(Path.GetTempPath());
            var outputPath  = gen.Generate(competition, section);

            //var generator = new TournamentBracketGenerator();
            //var result = generator.Generate(competition, section);

            return(View(new PrintModel {
                Path = outputPath
            }));                                              // Content(result);
        }
        public string Generate(CompetitionDetails details, CompetitionSection section)
        {
            var name = string.Format("{0}-{1}-{2}-{3}", details.Name, details.Id, Guid.NewGuid(), section);
            var outputPath = Path.Combine(m_targetPath, name + ".pdf");
            var infoPath = Path.Combine(m_targetPath, name + ".pcdf");
            var playersPath = Path.Combine(m_targetPath, name + ".players.csv");
            var schedulePath = Path.Combine(m_targetPath, name + ".schedule.csv");
            var inverter = new HebrewWordInverter();
            var info = GetGenerateInfo(details, inverter);
            
            var players = details.Players.Where(p => p.Section == section).ToArray();
            var matches = details.Matches.Where(m => m.Section == section).ToArray();
            SavePlayers(players, playersPath, inverter);
            SaveSchedule(matches, players, schedulePath);
            info.DataParticipantsFile = playersPath;
            info.DataScheduleFile = schedulePath;

            info.Write(infoPath);
            GeneratePdf(infoPath, outputPath);
            return outputPath;
        }
Example #13
0
    public UpdatePlayerPositionInfo AddPlayerToSection(int playerId, CompetitionSection section, CompetitionDetails details)
    {
        var result = default(UpdatePlayerPositionInfo);


        // rounds are in descending order, so first will be the max
        var maxRound = details.Matches.Where(m => m.Section == section).Max(m => m.Round);
        var match    =
            details.Matches.FirstOrDefault(
                m => m.Section == section && m.Round == 1 && (m.Player1.IsNull() || m.Player2.IsNull()));

        if (match.IsNotNull())
        {
            result          = new UpdatePlayerPositionInfo();
            result.MatchId  = match.Id;
            result.PlayerId = playerId;
            result.Position = match.Player1.IsNull() ? 0 : 1;
        }

        return(result);
    }
        public string Generate(CompetitionDetails details, CompetitionSection section)
        {
            var name         = string.Format("{0}-{1}-{2}-{3}", details.Name, details.Id, Guid.NewGuid(), section);
            var outputPath   = Path.Combine(m_targetPath, name + ".pdf");
            var infoPath     = Path.Combine(m_targetPath, name + ".pcdf");
            var playersPath  = Path.Combine(m_targetPath, name + ".players.csv");
            var schedulePath = Path.Combine(m_targetPath, name + ".schedule.csv");
            var inverter     = new HebrewWordInverter();
            var info         = GetGenerateInfo(details, inverter);

            var players = details.Players.Where(p => p.Section == section).ToArray();
            var matches = details.Matches.Where(m => m.Section == section).ToArray();

            SavePlayers(players, playersPath, inverter);
            SaveSchedule(matches, players, schedulePath);
            info.DataParticipantsFile = playersPath;
            info.DataScheduleFile     = schedulePath;

            info.Write(infoPath);
            GeneratePdf(infoPath, outputPath);
            return(outputPath);
        }
Example #15
0
        public ActionResult Create(int? competitionId, int? replacedPlayerId, Player player, CompetitionPlayerSource? competitionPlayerSource, CompetitionSection? competitionSection, CompetitionPlayerStatus? status, string reason)
        {
            var playersRepository = ServiceProvider.Get<IPlayersRepository>();
            var newPlayerId = playersRepository.Add(player);

            if (competitionId.HasValue)
            {
                var manager = ServiceProvider.Get<ICompetitionsManager>();
                if (replacedPlayerId.HasValue)
                {
                    manager.ReplacePlayer(competitionId.Value, replacedPlayerId.Value, newPlayerId, competitionPlayerSource.GetValueOrDefault(CompetitionPlayerSource.Regular), status.GetValueOrDefault(CompetitionPlayerStatus.Active), reason);
                }
                else
                {
                    manager.AddPlayerToCompetition(competitionId.Value, newPlayerId, competitionPlayerSource.GetValueOrDefault(CompetitionPlayerSource.Regular), competitionSection.GetValueOrDefault(CompetitionSection.Final));
                }
                return RedirectToAction("Details", "Competitions", new { id = competitionId.Value });
            }
            else
            {
                return RedirectToAction("Index");
            }
        }
Example #16
0
        public void PositionPlayerInSection(int competitionId, int playerId, CompetitionSection section, string matchCode = null)
        {
            var positioningEngine     = GetPositioningEngine(CompetitionMethod.Knockout);
            var competitionRepository = ServiceProvider.Get <ICompetitionRepository>();

            var competitionDetails = competitionRepository.GetCompetitionDetails(competitionId);
            var updatePlayerInfo   = new UpdatePlayerPositionInfo();

            if (matchCode.NotNullOrEmpty())
            {
                foreach (var match in competitionDetails.Matches)
                {
                    if (match.Player1Code == matchCode)
                    {
                        updatePlayerInfo.PlayerId = playerId;
                        updatePlayerInfo.MatchId  = match.Id;
                        updatePlayerInfo.Position = 0;
                    }
                    else if (match.Player2Code == matchCode)
                    {
                        updatePlayerInfo.PlayerId = playerId;
                        updatePlayerInfo.MatchId  = match.Id;
                        updatePlayerInfo.Position = 1;
                    }
                }
            }
            else
            {
                updatePlayerInfo = positioningEngine.AddPlayerToSection(playerId, section, competitionDetails);
            }

            if (updatePlayerInfo.IsNotNull())
            {
                var competitionMatchesRepository = ServiceProvider.Get <ICompetitionMatchesRepository>();
                competitionMatchesRepository.UpdatePlayersPosition(competitionId, new[] { updatePlayerInfo });
            }
        }
Example #17
0
        public string Generate(CompetitionDetails competition, CompetitionSection section)
        {
            var result = string.Empty;
            var map    = new Dictionary <int, Queue <MatchHeaderInfo> >();

            var sectionMatches = competition.Matches.Where(m => m.Section == section);

            foreach (var match in sectionMatches)
            {
                var matches = default(Queue <MatchHeaderInfo>);
                if (map.TryGetValue(match.Round, out matches))
                {
                    matches.Enqueue(match);
                }
                else
                {
                    matches = new Queue <MatchHeaderInfo>();
                    matches.Enqueue(match);
                    map[match.Round] = matches;
                }
            }
            var rounds = map.Keys.Max();

            using (var stringWriter = new StringWriter())
                using (var htmlWriter = new HtmlTextWriter(stringWriter))
                {
                    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Html);
                    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Head);

                    htmlWriter.AddAttribute(HtmlTextWriterAttribute.Href, VirtualPathUtility.ToAbsolute("~/Static/Css/bracket.css"));
                    htmlWriter.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");
                    htmlWriter.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet");
                    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Link);
                    htmlWriter.RenderEndTag();

                    htmlWriter.RenderEndTag();
                    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Body);

                    htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "header");
                    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                    htmlWriter.Write(competition.Name);
                    htmlWriter.RenderEndTag();

                    if (competition.MainRefereeName.NotNullOrEmpty())
                    {
                        htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "referee");
                        htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                        htmlWriter.Write(competition.MainRefereeName);
                        if (competition.MainRefereePhone.NotNullOrEmpty())
                        {
                            htmlWriter.Write(", ");
                            htmlWriter.Write(competition.MainRefereePhone);
                        }
                        htmlWriter.RenderEndTag();
                    }

                    if (competition.Site.NotNullOrEmpty())
                    {
                        htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "site");
                        htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                        htmlWriter.Write(competition.Site);
                        if (competition.SitePhone.NotNullOrEmpty())
                        {
                            htmlWriter.Write(", ");
                            htmlWriter.Write(competition.SitePhone);
                        }
                        htmlWriter.RenderEndTag();
                    }

                    htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "rounds clearfix");
                    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                    foreach (var round in sectionMatches.Select(m => m.Round).Distinct())
                    {
                        htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "round");
                        htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                        htmlWriter.Write(HtmlExtensions.RoundName(null, round));
                        htmlWriter.RenderEndTag();
                    }
                    htmlWriter.RenderEndTag();
                    var tournamentMatches = sectionMatches.Count();
                    if (tournamentMatches > 8)
                    {
                        tournamentMatches = ((tournamentMatches / 16) + 1) * 16;
                    }
                    htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "tournament" + tournamentMatches + "-wrap");
                    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                    htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "round6-top winner6");
                    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                    htmlWriter.RenderEndTag();

                    WriteRound(htmlWriter, 6, 0, map);

                    htmlWriter.RenderEndTag();
                    htmlWriter.RenderEndTag();
                    htmlWriter.RenderEndTag();
                    htmlWriter.Flush();
                    result = stringWriter.ToString();
                }

            return(result);
        }
Example #18
0
        public void AddPlayerToCompetition(int competitionId, int playerId, CompetitionPlayerSource source, CompetitionSection section)
        {
            var competitionsEngine     = ServiceProvider.Get <ICompetitionsEngine>();
            var competitionsRepository = ServiceProvider.Get <ICompetitionRepository>();
            var playersRepository      = ServiceProvider.Get <IPlayersRepository>();
            var player      = playersRepository.Get(playerId);
            var competition = competitionsRepository.GetCompetition(competitionId);

            if (competition == null)
            {
                throw new ArgumentException("Invalid competition id");
            }
            competitionsEngine.AddPlayersToCompetition(competitionId,
                                                       new[]
            {
                new AddCompetitionPlayerInfo()
                {
                    Player  = player,
                    Source  = source,
                    Section = section
                }
            });

            if ((int)competition.Status >= (int)CompetitionStatus.Positioned)
            {
                competitionsEngine.PositionPlayerInSection(competitionId, playerId, section);
            }
        }
Example #19
0
    public UpdatePlayerPositionInfo[] PositionPlayers(CompetitionDetails details, CompetitionSection section)
    {
        var helper       = new KnockoutMatchProvisioningEngineHelper();
        var engine       = new KnockoutCalculationEngine();
        var output       = engine.Calculate(details.Type.PlayersCount, details.Type.QualifyingToFinalPlayersCount, details.Players.Length);
        var sectionCodes =
            section == CompetitionSection.Final
                ? helper.GenerateMainDrawCodesQueue(output.TotalMainDrawPlayers, output.ActualMainDrawPlayers,
                                                    details.Type.QualifyingToFinalPlayersCount)
                : helper.GenerateQualifyingDrawCodes(output.TotalQualifyingPlayers, output.ActualQualifyingPlayers);

        var sectionPlayers = details.Players.Where(p => p.Section == section);
        var items          = new List <UpdatePlayerPositionInfo>();

        if (sectionCodes.Count > 0 && sectionPlayers.Any())
        {
            var map = new Dictionary <string, int>();
            foreach (var competitionPlayer in sectionPlayers)
            {
                map[sectionCodes.Dequeue()] = competitionPlayer.Id;
            }
            var sectionMatches = details.Matches.Where(m => m.Section == section);



            foreach (
                var match in sectionMatches.Where(m => m.Player1Code.NotNullOrEmpty() || m.Player2Code.NotNullOrEmpty())
                )
            {
                int playerId;
                if (match.Player1Code.NotNullOrEmpty())
                {
                    if (map.TryGetValue(match.Player1Code, out playerId))
                    {
                        items.Add(new UpdatePlayerPositionInfo()
                        {
                            MatchId  = match.Id,
                            PlayerId = playerId,
                            Position = 0
                        });
                    }
                }
                if (match.Player2Code.NotNullOrEmpty())
                {
                    if (map.TryGetValue(match.Player2Code, out playerId))
                    {
                        items.Add(new UpdatePlayerPositionInfo()
                        {
                            MatchId  = match.Id,
                            PlayerId = playerId,
                            Position = 1
                        });
                    }
                }
            }
        }
        return(items.ToArray());

        if (details.Type.QualifyingPlayersCount > 0 && section == CompetitionSection.Qualifying)
        {
            items.AddRange(this.GetQualifyingPlayersPositions(details));
        }
        if (section == CompetitionSection.Final)
        {
            items.AddRange(this.GetFinalPlayersPositions(details));
        }
        return((from item in items
                where item.IsNotNull <UpdatePlayerPositionInfo>()
                select item).ToArray <UpdatePlayerPositionInfo>());
    }
    public UpdatePlayerPositionInfo[] PositionPlayers(CompetitionDetails details, CompetitionSection section)
    {
        var helper = new KnockoutMatchProvisioningEngineHelper();
        var engine = new KnockoutCalculationEngine();
        var output = engine.Calculate(details.Type.PlayersCount, details.Type.QualifyingToFinalPlayersCount, details.Players.Length);
        var sectionCodes =
            section == CompetitionSection.Final
                ? helper.GenerateMainDrawCodesQueue(output.TotalMainDrawPlayers, output.ActualMainDrawPlayers,
                                                    details.Type.QualifyingToFinalPlayersCount)
                : helper.GenerateQualifyingDrawCodes(output.TotalQualifyingPlayers, output.ActualQualifyingPlayers);

        var sectionPlayers = details.Players.Where(p => p.Section == section);
        var items = new List<UpdatePlayerPositionInfo>();
        if (sectionCodes.Count > 0 && sectionPlayers.Any())
        {
            var map = new Dictionary<string, int>();
            foreach (var competitionPlayer in sectionPlayers)
            {
                map[sectionCodes.Dequeue()] = competitionPlayer.Id;
            }
            var sectionMatches = details.Matches.Where(m => m.Section == section);



            foreach (
                var match in sectionMatches.Where(m => m.Player1Code.NotNullOrEmpty() || m.Player2Code.NotNullOrEmpty())
                )
            {
                int playerId;
                if (match.Player1Code.NotNullOrEmpty())
                {
                    if (map.TryGetValue(match.Player1Code, out playerId))
                    {
                        items.Add(new UpdatePlayerPositionInfo()
                                      {
                                          MatchId = match.Id,
                                          PlayerId = playerId,
                                          Position = 0
                                      });
                    }
                }
                if (match.Player2Code.NotNullOrEmpty())
                {
                    if (map.TryGetValue(match.Player2Code, out playerId))
                    {
                        items.Add(new UpdatePlayerPositionInfo()
                                      {
                                          MatchId = match.Id,
                                          PlayerId = playerId,
                                          Position = 1
                                      });
                    }
                }


            }
        }
        return items.ToArray();
        
        if (details.Type.QualifyingPlayersCount > 0 && section == CompetitionSection.Qualifying)
        {
            items.AddRange(this.GetQualifyingPlayersPositions(details));
        }
        if (section == CompetitionSection.Final)
        {
            items.AddRange(this.GetFinalPlayersPositions(details));
        }
        return (from item in items
            where item.IsNotNull<UpdatePlayerPositionInfo>()
            select item).ToArray<UpdatePlayerPositionInfo>();
    }
        private IEnumerable<MatchHeaderInfo> CreateSectionMatches(int playersCount, CompetitionSection section, int? qualifyingToNextSection = default(int?))
        {
            var actualPlayersCount = playersCount - qualifyingToNextSection.GetValueOrDefault();
            var rounds = (int)Math.Log((playersCount), 2);
            var actualRounds = rounds - (qualifyingToNextSection.GetValueOrDefault() > 0 ? (int)Math.Log(qualifyingToNextSection.GetValueOrDefault(), 2) : 0);
            var matches = new List<MatchHeaderInfo>(playersCount);

            for (int i = 0; i < actualPlayersCount; i++)
            {
                var match = new MatchHeaderInfo();
                match.Section = section;
                match.Position = i;
                match.Round = rounds - Math.Max(0, (int)Math.Log((playersCount - (i + 1)), 2));
                match.IsFinal = (match.Round == actualRounds);// && ((actualRounds == 1) || (i < playersCount - 1));
                if (section == CompetitionSection.Final && match.Round == rounds - 1)
                {
                    match.IsSemiFinal = true;
                }
                match.Status = MatchStatus.Created;
                matches.Add(match);
            }
            var matchesByRound = matches.GroupBy(m => m.Round).ToArray();
            foreach (var roundMatches in matchesByRound)
            {
                var index = 0;
                foreach (var match in roundMatches)
                {
                    match.RoundRelativePosition = index++;
                }
            }
            return matches;
        }
 public ActionResult PositionCompetitionPlayers(int competitionId, CompetitionSection section)
 {
     var competitionManager = ServiceProvider.Get<ICompetitionsManager>();
     competitionManager.PositionCompetitionPlayers(competitionId, section);
     return RedirectToAction("Details", new { id = competitionId });
 }
        public string Generate(CompetitionDetails competition, CompetitionSection section)
        {
            var result = string.Empty;
            var map = new Dictionary<int, Queue<MatchHeaderInfo>>();

            var sectionMatches = competition.Matches.Where(m => m.Section == section);
            foreach (var match in sectionMatches)
            {
                var matches = default(Queue<MatchHeaderInfo>);
                if (map.TryGetValue(match.Round, out matches))
                {
                    matches.Enqueue(match);
                }
                else
                {
                    matches = new Queue<MatchHeaderInfo>();
                    matches.Enqueue(match);
                    map[match.Round] = matches;
                }
            }
            var rounds = map.Keys.Max();
            using (var stringWriter = new StringWriter())
            using (var htmlWriter = new HtmlTextWriter(stringWriter))
            {
                htmlWriter.RenderBeginTag(HtmlTextWriterTag.Html);
                htmlWriter.RenderBeginTag(HtmlTextWriterTag.Head);

                htmlWriter.AddAttribute(HtmlTextWriterAttribute.Href, VirtualPathUtility.ToAbsolute("~/Static/Css/bracket.css"));
                htmlWriter.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");
                htmlWriter.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet");
                htmlWriter.RenderBeginTag(HtmlTextWriterTag.Link);
                htmlWriter.RenderEndTag();

                htmlWriter.RenderEndTag();
                htmlWriter.RenderBeginTag(HtmlTextWriterTag.Body);

                htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "header");
                htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                htmlWriter.Write(competition.Name);
                htmlWriter.RenderEndTag();

                if (competition.MainRefereeName.NotNullOrEmpty())
                {
                    htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "referee");
                    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                    htmlWriter.Write(competition.MainRefereeName);
                    if (competition.MainRefereePhone.NotNullOrEmpty())
                    {
                        htmlWriter.Write(", ");
                        htmlWriter.Write(competition.MainRefereePhone);
                    }
                    htmlWriter.RenderEndTag();
                }

                if (competition.Site.NotNullOrEmpty())
                {
                    htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "site");
                    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                    htmlWriter.Write(competition.Site);
                    if (competition.SitePhone.NotNullOrEmpty())
                    {
                        htmlWriter.Write(", ");
                        htmlWriter.Write(competition.SitePhone);
                    }
                    htmlWriter.RenderEndTag();
                }

                htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "rounds clearfix");
                htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                foreach (var round in sectionMatches.Select(m => m.Round).Distinct())
                {
                    htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "round");
                    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                    htmlWriter.Write(HtmlExtensions.RoundName(null, round));
                    htmlWriter.RenderEndTag();
                }
                htmlWriter.RenderEndTag();
                var tournamentMatches = sectionMatches.Count();
                if (tournamentMatches > 8)
                {
                    tournamentMatches = ((tournamentMatches/16) + 1)*16;
                }
                htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "tournament" + tournamentMatches + "-wrap");
                htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                htmlWriter.AddAttribute(HtmlTextWriterAttribute.Class, "round6-top winner6");
                htmlWriter.RenderBeginTag(HtmlTextWriterTag.Div);
                htmlWriter.RenderEndTag();

                WriteRound(htmlWriter, 6, 0, map);

                htmlWriter.RenderEndTag();
                htmlWriter.RenderEndTag();
                htmlWriter.RenderEndTag();
                htmlWriter.Flush();
                result = stringWriter.ToString();

            }

            return result;
        }
    public UpdatePlayerPositionInfo AddPlayerToSection(int playerId, CompetitionSection section, CompetitionDetails details)
    {

        var result = default(UpdatePlayerPositionInfo);


            // rounds are in descending order, so first will be the max
            var maxRound = details.Matches.Where(m => m.Section == section).Max(m => m.Round);
            var match =
                details.Matches.FirstOrDefault(
                    m => m.Section == section && m.Round == 1 && (m.Player1.IsNull() || m.Player2.IsNull()));
            if (match.IsNotNull())
            {
                result = new UpdatePlayerPositionInfo();
                result.MatchId = match.Id;
                result.PlayerId = playerId;
                result.Position = match.Player1.IsNull() ? 0 : 1;
            }
        
        return result;
    }