private UpdatePlayerPositionInfo[] GetQualifyingPlayersPositions(CompetitionDetails details)
 {
     var items = Enumerable.Empty<UpdatePlayerPositionInfo>();
     var orderedMatches = (from m in details.Matches
         where m.Section == CompetitionSection.Qualifying
         orderby m.Position
         select m).Take<MatchHeaderInfo>((details.Type.QualifyingPlayersCount / 2)).ToArray<MatchHeaderInfo>();
     var qualifyingPlayers = (from p in details.Players
         where p.Section == CompetitionSection.Qualifying
         select p).ToArray<CompetitionPlayer>();
     if (qualifyingPlayers.Length > 0)
     {
         items = GetUpdatePlayerPositionInfos(PositionQualifyingPlayers(details, qualifyingPlayers), orderedMatches);
     }
     return items.ToArray<UpdatePlayerPositionInfo>();
 }
 private CompetitionPosition[] PositionFinalPlayersInCompetition(CompetitionDetails details, CompetitionPlayer[] players)
 {
     var positioningEngine = new FinalPositioningEngine();
     var positioningParameters = new FinalPositioningParameters
     {
         QualifyingToFinal = details.Type.QualifyingToFinalPlayersCount,
         Players = (from p in players select new Simple.SAMS.CompetitionEngine.Player
                                                 {
                                                     Id = p.Id, 
                                                     Rank = p.CompetitionRank,
                                                     AccumulatedScore = p.AccumulatedScore.GetValueOrDefault(),
                                                     AverageScore = p.AverageScore.GetValueOrDefault()
                                                 }).ToArray<Simple.SAMS.CompetitionEngine.Player>()
     };
     
     return positioningEngine.Evaluate(positioningParameters);
 }
        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;
        }
    private UpdatePlayerPositionInfo[] GetFinalPlayersPositions(CompetitionDetails details)
    {
        var items = Enumerable.Empty<UpdatePlayerPositionInfo>();
        var orderedMatches = (from m in details.Matches
            where m.Section == CompetitionSection.Final
            orderby m.Position
            select m).Take<MatchHeaderInfo>(details.Type.PlayersCount / 2).ToArray();

        var finalPlayers = (from p in details.Players
            where p.Section == CompetitionSection.Final
            select p).ToArray<CompetitionPlayer>();
        if (details.Type.QualifyingPlayersCount > 0)
        {
            finalPlayers = finalPlayers.Take(details.Type.PlayersCount - details.Type.QualifyingToFinalPlayersCount).ToArray();
        }
        if (finalPlayers.Length > 0)
        {
            var finalPositions = PositionFinalPlayersInCompetition(details, finalPlayers);
            items = GetUpdatePlayerPositionInfos(finalPositions, orderedMatches);
        }
        return items.ToArray<UpdatePlayerPositionInfo>();
    }
        public MatchHeaderInfo[] BuildMatches(CompetitionType competitionType, CompetitionDetails competitionDetails)
        {
            var helper = new KnockoutMatchProvisioningEngineHelper();
            var pMatches = helper.ProvisionMatches(competitionType.PlayersCount,
                                                  competitionType.QualifyingToFinalPlayersCount,
                                                  competitionDetails.Players.Length);
            var fMatches = pMatches.Where(m => m.SectionCode == "MD").ToArray();
            var qMatches = pMatches.Where(m => m.SectionCode == "Q").ToArray();

            var rankedPlayersCount = competitionType.PlayersCount - competitionType.QualifyingToFinalPlayersCount;
            var qPlayersCount = competitionDetails.Players.Length - rankedPlayersCount;
            if (qPlayersCount <= competitionType.QualifyingToFinalPlayersCount)
            {
                qPlayersCount = 0;
            }
            var matches = new List<MatchHeaderInfo>();
            var finalPlayersCount = PlayersCountCalculator.CalculatePlayersCount(rankedPlayersCount);
            var qualifyingPlayersCount = PlayersCountCalculator.CalculatePlayersCount(qPlayersCount);
            var finalSectionMatches = CreateSectionMatches(finalPlayersCount, CompetitionSection.Final).ToArray();
            var qualifyingSectionMatches = CreateSectionMatches(qualifyingPlayersCount, CompetitionSection.Qualifying, competitionType.QualifyingToFinalPlayersCount).ToArray();
            var consolationSectionMatches = CreateConselationMatches(finalPlayersCount);

            for (var i = 0; i < fMatches.Length; i++)
            {
                finalSectionMatches[i].Player1Code = fMatches[i].Player1Code;
                finalSectionMatches[i].Player2Code = fMatches[i].Player2Code;
            }
            for (var i = 0; i < qMatches.Length; i++)
            {
                qualifyingSectionMatches[i].Player1Code = qMatches[i].Player1Code;
                qualifyingSectionMatches[i].Player2Code = qMatches[i].Player2Code;
            }

            matches.AddRange(qualifyingSectionMatches);
            matches.AddRange(finalSectionMatches);
            matches.AddRange(consolationSectionMatches);
            return matches.ToArray();
        }
 private DrawGeneratorInfo GetGenerateInfo(CompetitionDetails details, HebrewWordInverter inverter)
 {
     var result = GetDefaultGenerateInfo();
     
     result.DrawTitle = inverter.Invert(details.Name);
     result.DrawType = inverter.Invert(details.SitePhone) + ", " + inverter.Invert(details.Site);
     result.DrawOtherInfo = inverter.Invert(details.MainRefereePhone) + ", " + inverter.Invert(details.MainRefereeName);
     result.DocumentAuthor = "Simple. SAMS - ITA " + DateTime.Now.Year.ToString();
     
     return result;
 }
        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;
        }
 private MatchPlayerViewModel GetPlayer(MatchPlayer player, CompetitionDetails competition)
 {
     var result = default(MatchPlayerViewModel);
     if (player.IsNotNull())
     {
         var cp = competition.Players.FirstOrDefault(p => p.Id == player.Id);
         if (cp.IsNotNull())
         {
             result = new MatchPlayerViewModel(player);
             result.Rank = cp.CompetitionRank;
         }
     }
     return result;
 }
    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 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;
    }
 private CompetitionPosition[] PositionQualifyingPlayers(CompetitionDetails details, CompetitionPlayer[] qualifyingPlayers)
 {
     var qualifyingPositioningEngine = new QualifyingPositioningEngine();
     var qualifyingPositioningParameters = new QualifyingPositionParameters
     {
         PlayersCount = details.Type.QualifyingPlayersCount,
         QualifyingCount = details.Type.QualifyingToFinalPlayersCount,
         Players = (from p in qualifyingPlayers.Take<CompetitionPlayer>(details.Type.QualifyingPlayersCount) select new Simple.SAMS.CompetitionEngine.Player
                                                                                                                        {
                                                                                                                            Id = p.Id, 
                                                                                                                            Rank = p.CompetitionRank,
                                                                                                                            AverageScore = p.AverageScore.GetValueOrDefault(),
                                                                                                                            AccumulatedScore = p.AccumulatedScore.GetValueOrDefault()
                                                                                                                        }).ToArray<Simple.SAMS.CompetitionEngine.Player>()
     };
     
     return qualifyingPositioningEngine.Evaluate(qualifyingPositioningParameters);
 }