public ActionResult Caller(int showId, int showDetailsId, int ringId, int showClassId)
        {
            var tmp = new CallingListModel
            {
                CallingList = new List<DogClassDetails>(),
                QueueList = new List<DogClassDetails>(),
                CourseDetails = new Domain.Managers.ClassManager().GetCourseDetails(showClassId)
            };
            var callingList = new ShowClasses().GetCallingList(showId, showClassId);

            foreach (var item in callingList)
            {
                var us = new UserShows(item.UserId, showId);
                tmp.CallingList.Add(new DogClassDetails
                {
                    ClassId = showClassId,
                    DogId = item.DogId,
                    HandlerType = us.HandlerType,
                    RO = item.Ro,
                    Status = item.Status,
                    HandlerName = Utils.TitleCaseString(item.Name),
                    DogName = Utils.TitleCaseString(item.KcName),
                    Lho = item.Lho,
                    Grade = item.Grade,
                    Veteran = item.Veteran
                });
            }

            var queued = new Fpp.Domain.Managers.QueueManager().GetQueued(showClassId);
            foreach(var item in queued )
            {
                var details = tmp.CallingList.First(x => x.DogId == item.DogId);

                tmp.QueueList.Add(new DogClassDetails {
                    ClassId= showClassId,
                    DogId = item.DogId,
                    RO = details.RO,
                    DogName = details.DogName,
                    HandlerName = details.HandlerName,
                    HandlerType = details.HandlerType,
                    Position = item.Position,
                    Grade = details.Grade,
                    Lho = details.Lho,
                    Veteran = details.Veteran
                });
            }

            var show = new Shows(showId);
            var showDetails = new ShowDetails(showDetailsId);
            var showClass = new ShowClasses(showClassId);
            ViewBag.ShowName = show.ShowName;
            ViewBag.Day = showDetails.ShowDate.ToString("ddd, dd MMM");
            ViewBag.ClassName = showClass.NormalName();
            ViewBag.ClassId = showClassId;
            ViewBag.RingId = ringId;
            ViewBag.ShowId = showId;

            return View(tmp);
        }
        public ActionResult Scoreboard(int showId, int showDetailsId, int showClassId)
        {
            var scoreboard = Fpp.Domain.Managers.ResultsManager.GetResults(showClassId);

            var show = new Shows(showId);
            var showDetails = new ShowDetails(showDetailsId);
            var showClass = new ShowClasses(showClassId);
            ViewBag.ShowName = show.ShowName;
            ViewBag.Day = showDetails.ShowDate.ToString("ddd, dd MMM");
            ViewBag.ClassName = showClass.NormalName();
            ViewBag.ClassId = showClassId;
            ViewBag.ShowId = showId;
            return View(scoreboard);
        }
        public static List<DogClassModel> GetDogsInClass(int ClassId)
        {
            var show = ShowClasses.GetShowFromClassId(ClassId);
            var cls = new ShowClasses(ClassId);
            var list = new List<DogClassModel>();
            String moduleSettings = ModuleConfig.GetSettings();
            Data.DogClasses dc = new Data.DogClasses(moduleSettings);
            DataSet ds;

            if (isMultiDog(cls.EntryType))
            {
                ds = dc.GetDogForClass(ClassId);
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    list.Add(new DogClassModel
                    {
                        DogClassesId = Convert.ToInt32(row["DogClassesId"]),
                        UserId = Convert.ToInt32(row["UserId"]),
                        UserName = row["Name"].ToString(),
                        KCName = row["KCName"].ToString(),
                        DogId = Convert.ToInt32(row["DogId"]),
                        Grade = Convert.ToInt32(row["Grade"]),
                        RO = Convert.ToInt32(row["RO"]),
                        Lho = Convert.ToInt32(row["Lho"]),
                        Height = ShowClasses.expandHeight(row),
                        HandlerAgeAtShow = GetAgeFromShow(row, show)
                    });
                }
            }
            else
            {
                ds = dc.GetDogForClass(ClassId);
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    list.Add(new DogClassModel
                    {
                        DogClassesId = Convert.ToInt32(row["DogClassesId"]),
                        UserId = Convert.ToInt32(row["UserId"]),
                        UserName = row["Name"].ToString(),
                        KCName = row["KCName"].ToString(),
                        DogId = Convert.ToInt32(row["DogId"]),
                        Grade = Convert.ToInt32(row["Grade"]),
                        RO = Convert.ToInt32(row["RO"]),
                        Lho = Convert.ToInt32(row["Lho"]),
                        Height = ShowClasses.expandHeight(row),
                        HandlerAgeAtShow = GetAgeFromShow(row, show)
                    });
                }
            }

            return list;
        }
        public static List<ShowClassDto> GetClassesForRingId(int RingID)
        {
            String moduleSettings = ModuleConfig.GetSettings();
            Fpp.Data.Rings ring = new Fpp.Data.Rings(moduleSettings);
            var ds = ring.GetClassesForRing(RingID);
            var tmp = new List<ShowClassDto>();

            foreach(DataRow row in ds.Tables[0].Rows)
            {
                var cls = new ShowClasses(Convert.ToInt32(row["ClassId"]));

                tmp.Add(new ShowClassDto {
                    ClassId = cls.ID,
                    ClassName = cls.NormalName(),
                    DogsInClass = Convert.ToInt32(row["DogsInClass"])
                });
            }

            return tmp;
        }
        private Models.RingDetails CreateRing(ShowDetails day, Rings ring)
        {
            RingDetails rd = new RingDetails
            {
                RingId = ring.ID,
                RingNo = ring.RingNo,
                JudgeDetails = new List<JudgeDetails>(),
                ShowDetailsId = ring.ShowDetailsID
            };
            DataSet judgesDS = Rings.GetJudgesForRing(ring.ID);
            if (judgesDS.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow judgeRow in judgesDS.Tables[0].Rows)
                {
                    Judge judge = new Judge(judgeRow);
                    var judgeDetails = new JudgeDetails
                    {
                        JudgeId = judge.ID,
                        JudgeName = judge.Name,
                        RingOrder = judge.RingOrder,
                        ClassDetails = new List<ClassDetails>(),
                        HelperDetails = new List<Helper>()
                    };

                    var helperDS = Business.Helpers.GetHelpersForRing(day, ring.ID);
                    if (helperDS.Tables.Count > 0)
                    {
                        foreach (DataRow helperRow in helperDS.Tables[0].Rows)
                        {
                            Business.Helpers h = new Business.Helpers(helperRow);
                            String job = Fpp.Core.Utils.expandJob(h.Job, h.JobDetails);

                            Helper hd = new Helper
                            {
                                HelperId = h.ID,
                                HelperName = h.Name,
                                JobDescription = Business.Helpers.expandHelper(h)
                            };
                            judgeDetails.HelperDetails.Add(hd);
                        }
                    }

                    DataSet classesDS = judge.getClassesForJudge();
                    if (classesDS.Tables.Count > 0)
                    {
                        foreach (DataRow classRow in classesDS.Tables[0].Rows)
                        {
                            ShowClasses sc = new ShowClasses(classRow);
                            var Part = Convert.ToInt32(classRow["Part"]);
                            var PartNo = "";
                            var ClassName = classRow["ShortName"].ToString();
                            if (sc.EntryType == 10)
                            {
                                ClassName = classRow["Name"].ToString();
                                if (ClassName.Contains("Jumping"))
                                    ClassName = "Jumping";
                                else if (ClassName.Contains("Agility"))
                                    ClassName = "Agility";
                                else if (ClassName.Contains("Final"))
                                    ClassName = "Final";
                                ClassName = string.Format("{0} {1} {2}",
                                    ShowClasses.expandHeightShort(classRow),
                                    sc.ShortClassName,
                                    ClassName);
                            }
                            else
                            {
                                PartNo = (Part == 0 ? "" : string.Format("Pt {0}", Part));
                                ClassName = string.Format("{0} {1} {2} {3} {4} {5}",
                                    ShowClasses.expandHeightShort(classRow),
                                    ShowClasses.expandCatagoryShort(classRow),
                                    ClassName,
                                    ShowClasses.shortenName(classRow),
                                    ShowClasses.shortenGrades(classRow),
                                    PartNo);
                            }
                            judgeDetails.ClassDetails.Add(new ClassDetails
                            {
                                ClassId = sc.ID,
                                ClassNo = sc.ClassNo,
                                PartNo = Part,
                                DogsInClass = Fpp.Core.Utils.CalcDogsInCalc(classRow),
                                ClassName = ClassName,
                                Height = sc.Height
                            });
                        }
                    }
                    rd.JudgeDetails.Add(judgeDetails);
                }
            }
            return rd;
        }
        private Models.RingDetails CreateRing(ShowDetails day, Rings ring)
        {
            RingDetails rd = new RingDetails
            {
                JudgeDetails = new List<JudgeDetails>(),
                ShowDetailsId = ring.ShowDetailsID
            };
            DataSet judgesDS = Rings.GetJudgesForRing(ring.ID);
            if (judgesDS.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow judgeRow in judgesDS.Tables[0].Rows)
                {
                    Judge judge = new Judge(judgeRow);
                    var judgeDetails = new JudgeDetails
                    {
                        JudgeId = judge.ID,
                        JudgeName = judge.Name,
                        ClassDetails = new List<ClassDetails>(),
                        HelperDetails = new List<Helper>()
                    };

                    var helperDs = Business.Helpers.GetHelpersForRing(day, ring.ID);
                    if (helperDs.Tables.Count > 0)
                    {
                        foreach (DataRow helperRow in helperDs.Tables[0].Rows)
                        {
                            var h = new Business.Helpers(helperRow);
                            var hd = new Helper
                            {
                                HelperId = h.ID,
                                HelperName = h.Name,
                                JobDescription = h.Job
                            };
                            judgeDetails.HelperDetails.Add(hd);
                        }
                    }

                    DataSet classesDS = Rings.GetClassesForRing(ring.ID);
                    classesDS = judge.getClassesForJudge();
                    if (classesDS.Tables.Count > 0)
                    {
                        foreach (DataRow classRow in classesDS.Tables[0].Rows)
                        {

                            ShowClasses sc = new ShowClasses(classRow);
                            judgeDetails.ClassDetails.Add(new ClassDetails
                            {
                                ClassId = sc.ID,
                                ClassNo = sc.ClassNo,
                                DogsInClass = Fpp.Core.Utils.CalcDogsInCalc(classRow),
                                ClassName =
                                    $"{ShowClasses.expandHeightShort(classRow)} {ShowClasses.expandCatagoryShort(classRow)} {classRow["ShortName"]} {classRow["Name"]} {ShowClasses.shortenGrades(classRow)}"
                            });
                        }
                    }
                    rd.JudgeDetails.Add(judgeDetails);
                }
            }
            return rd;
        }
        public JsonResult QueueUpdate(int showId, int showClassId)
        {
            var tmp = new ScrimerModel
            {
                CallingList = new List<DogClassDetails>(),
                QueueList = new List<DogClassDetails>()
            };
            var callingList = new ShowClasses().GetCallingList(showId, showClassId);
            foreach (var item in callingList)
            {
                var us = new UserShows(item.UserId, showId);
                tmp.CallingList.Add(new DogClassDetails
                {
                    ClassId = showClassId,
                    DogId = item.DogId,
                    HandlerType = us.HandlerType,
                    RO = item.Ro,
                    Status = item.Status,
                    HandlerName = Utils.TitleCaseString(item.Name),
                    DogName = Utils.TitleCaseString(item.KcName),
                    Lho = item.Lho,
                    Grade = item.Grade
                });
            }

            var queued = new Fpp.Domain.Managers.QueueManager().GetQueued(showClassId);
            foreach (var item in queued)
            {
                var details = tmp.CallingList.First(x => x.DogId == item.DogId);

                tmp.QueueList.Add(new DogClassDetails
                {
                    ClassId = showClassId,
                    DogId = item.DogId,
                    RO = details.RO,
                    DogName = details.DogName,
                    HandlerName = details.HandlerName,
                    HandlerType = details.HandlerType,
                    Lho = details.Lho,
                    Grade = details.Grade
                });
            }
            return Json(new
            {
                CallingList = tmp.CallingList,
                QueueList = queued,
                Status = 0,
            });
        }
        public void ResetNumbersForDay(int ShowID, int ShowDetailsID)
        {
            DataSet ds = _showClasses.getAllClassesForShow(ShowID);
            if (ds.Tables.Count > 0)
            {
                int rowCnt = 1;
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    ShowClasses sc = new ShowClasses(row);
                    sc.ClassNo = rowCnt;
                    sc.Update();

                    rowCnt++;

                }
            }
        }
 public static void UpdateRings(Fpp.Core.Models.RPRingClassUpdate RingClassUpdate)
 {
     foreach (var Ring in RingClassUpdate.Rings)
     {
         if (Ring.Classes != null)
         {
             int pos = 1;
             foreach (int ClsId in Ring.Classes)
             {
                 ShowClasses sc = new ShowClasses(ClsId);
                 sc.Position = pos++;
                 sc.RingID = Ring.Id;
                 sc.Update();
             }
         }
     }
 }
        public void TrailerSheets(Document doc, int ShowId)
        {
            Font smallFont = new Font(Font.COURIER, 8, Font.NORMAL, Color.BLACK);
            Font normalFont = new Font(Font.COURIER, 10, Font.NORMAL, Color.BLACK);
            Font mediumFont = new Font(Font.HELVETICA, 20, Font.NORMAL, Color.BLACK);
            ShowClasses sc = new ShowClasses();

            List<Rings> AllRings = new List<Rings>();
            var showDetailsList = ShowDetails.GetShowDetails(ShowId);
            Shows show = new Shows(ShowId);
            var pageBreaks = 0;
            foreach (var showDetails in showDetailsList)
            {
                Rings rings = new Rings();
                var ringsForDays = Rings.GetRingsForShowDayList(showDetails.ID);
                //            var groupByRing = ringsForDays.GroupBy(x => x.RingNo);
                int lastRingNo = 0;
                foreach (Rings ring in ringsForDays)
                {
                    if (ring.ID > -1 && lastRingNo != ring.RingNo)
                    {
                        lastRingNo = ring.RingNo;
                        if (pageBreaks % 3 == 0 || ring.RingNo == 1)
                        {
                            doc.NewPage();
                            pageBreaks = 0;
                        }

                        DataSet judgesDS = Rings.GetJudgesForRing(ring.ID);
                        if (judgesDS.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow judgeRow in judgesDS.Tables[0].Rows)
                            {
                                Judge judge = new Judge(judgeRow);
                                TrailerSheetRing(doc, show, showDetails, ring, judge, "", lastRingNo);
                            }
                        }
                    }
                    pageBreaks++;
                }
            }
            doc.NewPage();
        }
        public void ScribeSheets(Document doc, int showId, int ringId, PdfWriter writer )
        {
            var font = new Font(Font.HELVETICA, 10, Font.NORMAL, Color.BLACK);
            var smallFont = new Font(Font.HELVETICA, 8, Font.NORMAL, Color.BLACK);
            var totalsFont = new Font(Font.HELVETICA, 14, Font.BOLD, Color.BLACK);
            var bigBoyFont = new Font(Font.HELVETICA, 20, Font.BOLD, Color.BLACK);
            var bigBoyFont2 = new Font(Font.HELVETICA, 25, Font.BOLD, Color.BLACK);
            var blankCell = new PdfPCell(new Phrase(new Chunk("", font)));
            var sc = new ShowClasses();
            var currentRing = new Rings(ringId);
            var multiClasses = TeamPairsManager.GetTeamPairClasses(showId);
            var multiTeams = TeamPairsManager.GetTeamPairsForShow(showId, multiClasses);
            var showClasses = ShowClasses.GetAllClassesForShowRing(showId, ringId);
            foreach (var showClass in showClasses)
            {
                var callingList = sc.GetCallingList(showId, showClass.ID);

                var grades = showClass.Grades;
                if (grades.Length == 1)
                {
                    grades = "Grade " + grades;
                }
                else
                {
                    grades = "Grades " + grades[0] + "-" + grades[grades.Length - 1];
                }
                var ptable = new PdfPTable(1);
                var tmp = $"Class {showClass.ClassNo}";
                var cell = new PdfPCell(new Phrase(new Chunk(tmp, bigBoyFont2)))
                {
                    BorderWidth = 0,
                    Padding = 5,
                    HorizontalAlignment = Element.ALIGN_MIDDLE,
                    VerticalAlignment = Element.ALIGN_CENTER
                };
                ptable.AddCell(cell);

                if (showClass.EntryType == 10)
                {
                    tmp = $"{showClass.longHeight} {showClass.LongClassName} {showClass.ClassName}";
                }
                else
                {
                    tmp =
                        $"{showClass.NormalName(withClassNo: false)} {(showClass.Part > 0 ? "Part " + showClass.Part : "")} ";
                }
                cell = new PdfPCell(new Phrase(new Chunk(tmp, totalsFont)))
                {
                    BorderWidth = 0,
                    Padding = 5,
                    HorizontalAlignment = Element.ALIGN_MIDDLE,
                    VerticalAlignment = Element.ALIGN_CENTER
                };
                ptable.AddCell(cell);

                if (showClass.EntryType != 10)
                {
                    tmp = $"{grades}";
                    cell = new PdfPCell(new Phrase(new Chunk(tmp, totalsFont)))
                    {
                        BorderWidth = 0,
                        Padding = 5,
                        FixedHeight = 100f,
                        HorizontalAlignment = Element.ALIGN_MIDDLE,
                        VerticalAlignment = Element.ALIGN_CENTER
                    };
                    ptable.AddCell(cell);
                }

                tmp = $"Ring {currentRing.RingNo}";
                cell = new PdfPCell(new Phrase(new Chunk(tmp, totalsFont)))
                {
                    BorderWidth = 0,
                    Padding = 5,
                    FixedHeight = 30f,
                    HorizontalAlignment = Element.ALIGN_MIDDLE
                };
                ptable.AddCell(cell);

                tmp = $"Ring Order = {showClass.Position}";
                cell = new PdfPCell(new Phrase(new Chunk(tmp, totalsFont)))
                {
                    BorderWidth = 0,
                    Padding = 5,
                    FixedHeight = 30f,
                    HorizontalAlignment = Element.ALIGN_MIDDLE
                };
                ptable.AddCell(cell);

                doc.Add(ptable);
                doc.NewPage();

                if (TeamPairsManager.isMultiDog(showClass.EntryType))
                {
                    float[] colWidths = { 300, 150 };
                    var callingListTbl = new PdfPTable(colWidths);

                    var teamsForClass = multiTeams.Where(t => t.ClassId == showClass.ID).OrderBy(t => t.RO);
                    foreach (var team in teamsForClass)
                    {

                        tmp = $"Class {showClass.NormalName()}: {(showClass.Part > 0 ? "Part " + showClass.Part : "")}";
                        cell = new PdfPCell(new Phrase(new Chunk(tmp, notSoBigFont)))
                        {
                            BorderWidth = 2,
                            BorderColorRight = Color.BLACK,
                            BorderColorBottom = Color.BLACK,
                            Padding = 5,
                            PaddingTop = 1,
                            PaddingLeft = 2,
                            FixedHeight = 50f
                        };
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk(team.RO.ToString(), bigBoyFont)))
                        {
                            BorderWidth = 2,
                            BorderColorLeft = Color.BLACK,
                            BorderColorBottom = Color.BLACK,
                            HorizontalAlignment = Element.ALIGN_CENTER,
                            Padding = 5
                        };
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk("Course Time", notSoBigFont)))
                        {
                            BorderWidth = 2,
                            Padding = 5,
                            BorderColorRight = Color.BLACK,
                            HorizontalAlignment = Element.ALIGN_RIGHT
                        };
                        callingListTbl.AddCell(cell);
                        cell = new PdfPCell(new Phrase(new Chunk(" ", notSoBigFont)))
                        {
                            BorderWidth = 2,
                            Padding = 5,
                            BorderColorRight = Color.BLACK,
                            HorizontalAlignment = Element.ALIGN_RIGHT
                        };
                        callingListTbl.AddCell(cell);

                        if (TeamPairsManager.isTeam(showClass.EntryType))
                        {
                            cell =
                                new PdfPCell(
                                    new Phrase(new Chunk(team.TeamDetails.TeamName.Replace("&#39;", "'"), bold12)))
                                {
                                    PaddingBottom = 5,
                                    BorderWidth = 0,
                                    BorderWidthBottom = 1,
                                    HorizontalAlignment = Element.ALIGN_CENTER,
                                    BorderColor = Color.LIGHT_GRAY,
                                    Colspan = 2
                                };
                            callingListTbl.AddCell(cell);
                            var dogCnt = 0;
                            var reserves = "";
                            foreach (var md in team.Members)
                            {
                                if (dogCnt < team.DogCount)
                                {
                                    cell = new PdfPCell(new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(md.DogName), normal8)));
                                    cell.BorderWidth = 0;
                                    callingListTbl.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(md.HandlerName), normal8)));
                                    cell.BorderWidth = 0;
                                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                                    callingListTbl.AddCell(cell);
                                }
                                else
                                {
                                    if (md.HandlerName.Length > 0  )
                                    {
                                        if (reserves.Length > 0) reserves += ",";
                                        reserves +=
                                            $"{Utils.TitleCaseString(md.HandlerName)} & {Utils.TitleCaseString(md.DogName)}";
                                    }
                                }
                                dogCnt++;
                            }
                            if (reserves.Length > 0)
                            {
                                cell = new PdfPCell(new Phrase(new Chunk("Reserves:" + reserves, italic8)))
                                {
                                    BorderWidth = 0,
                                    Colspan = 2
                                };
                                callingListTbl.AddCell(cell);
                            }
                            doc.Add(callingListTbl);

                            callingListTbl = new PdfPTable(colWidths);
                            var linecnt = writer.GetVerticalPosition(false) - doc.BottomMargin;
                            cell = new PdfPCell
                            {
                                BorderWidth = 0,
                                Colspan = 2,
                                FixedHeight = writer.PageSize.Height - linecnt - 60
                            };
                            callingListTbl.AddCell(cell);
                            doc.Add(callingListTbl);

                        }
                        else
                        {
                            var memberTable = new PdfPTable(new float[] { 300, 300 });
                            var memberCell = new PdfPCell(memberTable)
                            {
                                BorderWidth = 0,
                                Colspan = 2,
                                PaddingBottom = 10
                            };
                            var dogCnt = 0;
                            foreach (var md in team.Members)
                            {
                                if (dogCnt < team.DogCount)
                                {
                                    cell =
                                        new PdfPCell(
                                            new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(md.HandlerName), font)))
                                        {
                                            BorderWidth = 0
                                        };
                                    memberTable.AddCell(cell);

                                    cell =
                                        new PdfPCell(
                                            new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(md.DogName), font)))
                                        {
                                            BorderWidth = 0
                                        };
                                    memberTable.AddCell(cell);
                                }
                                dogCnt++;
                            }
                            memberCell.FixedHeight = 180f;
                            callingListTbl.AddCell(memberCell);
                            doc.Add(callingListTbl);
                        }

                        callingListTbl = new PdfPTable(colWidths);
                        cell = new PdfPCell(new Phrase(new Chunk("Time", notSoBigFont)))
                        {
                            BorderWidth = 2,
                            BorderColorRight = Color.BLACK,
                            BorderColorBottom = Color.BLACK,
                            Padding = 5,
                            HorizontalAlignment = Element.ALIGN_CENTER
                        };
                        callingListTbl.AddCell(cell);
                        callingListTbl.AddCell(blankCell);

                        cell = new PdfPCell(new Phrase(new Chunk("Course Faults", notSoBigFont)))
                        {
                            BorderWidth = 2,
                            BorderColorRight = Color.BLACK,
                            BorderColorBottom = Color.BLACK,
                            Padding = 5,
                            HorizontalAlignment = Element.ALIGN_CENTER
                        };
                        callingListTbl.AddCell(cell);
                        callingListTbl.AddCell(blankCell);

                        cell = new PdfPCell(new Phrase(new Chunk("Time Faults", notSoBigFont)))
                        {
                            BorderWidth = 2,
                            BorderColorRight = Color.BLACK,
                            BorderColorBottom = Color.BLACK,
                            Padding = 5,
                            HorizontalAlignment = Element.ALIGN_CENTER
                        };
                        callingListTbl.AddCell(cell);
                        callingListTbl.AddCell(blankCell);

                        cell = new PdfPCell(new Phrase(new Chunk("Totals Faults", notSoBigFont)))
                        {
                            BorderWidth = 2,
                            BorderColorRight = Color.BLACK,
                            BorderColorBottom = Color.BLACK,
                            Padding = 5,
                            HorizontalAlignment = Element.ALIGN_CENTER
                        };
                        callingListTbl.AddCell(cell);
                        callingListTbl.AddCell(blankCell);
                        doc.Add(callingListTbl);
                        doc.NewPage();

                        doc.NewPage();
                        callingListTbl = new PdfPTable(colWidths);

                    }
                    doc.Add(callingListTbl);

                }
                else {
                    foreach (var item in callingList)
                    {
                        if (item.Category == 0 && showClass.EntryType != 10)
                        {
                            var tbl = new PdfPTable(1);
                            tmp = item.Grade == 99 ? "Veteran" : $"Grade {item.Grade}";
                            cell = new PdfPCell(new Phrase(new Chunk(tmp, bigBoyFont2)))
                            {
                                BackgroundColor = Color.LIGHT_GRAY,
                                BorderWidth = 2,
                                Padding = 9,
                                PaddingTop = 4,
                                HorizontalAlignment = Element.ALIGN_RIGHT
                            };
                            tbl.AddCell(cell);
                            doc.Add(tbl);
                        }

                        float[] colWidths = { 300, 150 };
                        var callingListTbl = new PdfPTable(colWidths);
                        tmp = showClass.EntryType == 10 ?
                            $"Class {showClass.ClassNo}: {showClass.longHeight} {showClass.LongClassName} {showClass.ClassName}"
                            : $"Class {showClass.ClassNo}: {showClass.NormalName(withClassNo: false)} {(showClass.Part > 0 ? "Part " + showClass.Part : "")}";
                        cell = new PdfPCell(new Phrase(new Chunk(tmp, notSoBigFont)))
                        {
                            BorderWidth = 2,
                            BorderColorRight = Color.BLACK,
                            BorderColorBottom = Color.BLACK,
                            Padding = 5,
                            PaddingTop = 1,
                            PaddingLeft = 2,
                            FixedHeight = 50f
                        };
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk($"{item.Ro}", bigBoyFont)))
                        {
                            BorderWidth = 2,
                            BorderColorLeft = Color.BLACK,
                            BorderColorBottom = Color.BLACK,
                            HorizontalAlignment = Element.ALIGN_CENTER,
                            Padding = 5
                        };
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk("Course Time", notSoBigFont)))
                        {
                            BorderWidth = 2,
                            Padding = 5,
                            BorderColorRight = Color.BLACK,
                            HorizontalAlignment = Element.ALIGN_RIGHT
                        };
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk("", notSoBigFont)))
                        {
                            BorderWidth = 2,
                            Padding = 5,
                            BorderColorBottom = Color.BLACK
                        };
                        callingListTbl.AddCell(cell);

                        var handlerName = item.Name;
                        User user;
                        if (item.DefaultHandlerId > 0)
                        {
                            user = new User(item.DefaultHandlerId);
                            handlerName = user.Name;
                        }
                        if (item.AltHandlerId> 0)
                        {
                            user = new User(item.AltHandlerId);
                            handlerName = user.Name;
                        }

                        if (showClass.EntryType == 5 || showClass.EntryType == 9)
                        {
                            cell =
                                new PdfPCell(new Phrase(new Chunk($"{Utils.TitleCaseString(handlerName)}", smallFont)))
                                {
                                    BorderWidth = 0,
                                    Colspan = 1,
                                    HorizontalAlignment = Element.ALIGN_LEFT
                                };
                            callingListTbl.AddCell(cell);

                            cell = new PdfPCell(new Phrase(new Chunk(
                                $"{Utils.TitleCaseString(item.KcName),-10}", smallFont)))
                            {
                                Colspan = 1,
                                HorizontalAlignment = Element.ALIGN_RIGHT,
                                BorderWidth = 0
                            };
                        }
                        else
                        {
                            cell =
                                new PdfPCell(new Phrase(new Chunk($"{Utils.TitleCaseString(handlerName)}", notSoBigFont)))
                                {
                                    BorderWidth = 0,
                                    Colspan = 2
                                };
                            callingListTbl.AddCell(cell);
                            callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk(
                                $"{item.RingNumber,-10} {Utils.TitleCaseString(item.KcName)}",
                                notSoBigFont)))
                            {
                                BorderWidth = 0,
                                Colspan = 2
                            });

                            callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk($"{item.Breed}", notSoBigFontItalic))) { BorderWidth = 0, Colspan = 2});

                            cell = new PdfPCell(new Phrase(new Chunk($"{(item.Lho == 0 ? "" : "Lower Height")}", Bold18Black)))
                            {
                                BorderWidth = 0,
                                Colspan = 2,
                                PaddingTop = 10
                            };
                        }

                        int[] extendHeight = { 1, 2, 3, 7, 10, 11 };
                        if (extendHeight.Any(h => h == showClass.EntryType))
                        {
                            cell.FixedHeight = 160f;
                        }
                        cell.Colspan = 2;
                        callingListTbl.AddCell(cell);

                        doc.Add(callingListTbl);
                        callingListTbl = new PdfPTable(colWidths);
                        cell = new PdfPCell(new Phrase(new Chunk("Time", notSoBigFont)))
                        {
                            BorderWidth = 2,
                            BorderColorRight = Color.BLACK,
                            BorderColorBottom = Color.BLACK,
                            Padding = 5,
                            HorizontalAlignment = Element.ALIGN_CENTER
                        };
                        callingListTbl.AddCell(cell);
                        callingListTbl.AddCell(blankCell);

                        cell = new PdfPCell(new Phrase(new Chunk("Course Faults", notSoBigFont)))
                        {
                            BorderWidth = 2,
                            BorderColorRight = Color.BLACK,
                            BorderColorBottom = Color.BLACK,
                            Padding = 5,
                            HorizontalAlignment = Element.ALIGN_CENTER
                        };
                        callingListTbl.AddCell(cell);
                        callingListTbl.AddCell(blankCell);

                        cell = new PdfPCell(new Phrase(new Chunk("Time Faults", notSoBigFont)))
                        {
                            BorderWidth = 2,
                            BorderColorRight = Color.BLACK,
                            BorderColorBottom = Color.BLACK,
                            Padding = 5,
                            HorizontalAlignment = Element.ALIGN_CENTER
                        };
                        callingListTbl.AddCell(cell);
                        callingListTbl.AddCell(blankCell);

                        cell = new PdfPCell(new Phrase(new Chunk("Totals Faults", notSoBigFont)))
                        {
                            BorderWidth = 2,
                            BorderColorRight = Color.BLACK,
                            BorderColorBottom = Color.BLACK,
                            Padding = 5,
                            HorizontalAlignment = Element.ALIGN_CENTER
                        };
                        callingListTbl.AddCell(cell);
                        callingListTbl.AddCell(blankCell);
                        doc.Add(callingListTbl);
                        doc.NewPage();

                    }
                }
            }
        }
        public void GenerateROs(int ShowId, int ClassId)
        {
            List<DogClassCount> dcCounts = DogClasses.GetEntryCountsByClassId(ShowId, ClassId);
            ShowClasses sc = new ShowClasses(ClassId);
            var dogclsids = getDogClassIDFromClass(ClassId, sc.Lho);
            if (sc.Lho == 2 )
            {
                dcCounts = dcCounts.OrderByDescending(d => d.Lho).ToList();
            }

            for (var ii = 0; ii < dcCounts.Count; ii++)
            {
                var dogCount = dcCounts[ii];
                int[] ROs = new int[dogCount.Count];
                if (dogCount.Part > 0 || sc.Lho > 0)
                {
                    RORange range = (dogCount.Part > 0
                            ? GetRORange(ClassId)
                            : new RORange {
                                Count = dogCount.Count,
                                Min = ( ii == 0 ? 1 : dcCounts[ii - 1].Count + 1),
                                Max = (ii == 0 ? dogCount.Count : dcCounts[ii - 1].Count + dogCount.Count )
                            });
                    if (range.Min == 0)
                    {
                        range.Min = (dogCount.Part - 1) * range.Count + 1;
                        range.Max = range.Min + range.Count - 1;
                    }
                    dogCount.Count = range.Max - range.Min + 1;
                    ROs = new int[dogCount.Count];
                    int i = 0;
                    while (range.Min + i <= range.Max)
                    {
                        ROs[i] = range.Min + i;
                        i++;
                    }
                }
                else
                {
                    for (int i = 0; i < dogCount.Count; i++)
                    {
                        ROs[i] = i + 1;
                    }
                }

                Random r1 = new Random();
                for (int i = 0; i < dogCount.Count; i++)
                {
                    int p1 = r1.Next(dogCount.Count);
                    int p2 = r1.Next(dogCount.Count);

                    int tmp = ROs[p1];
                    ROs[p1] = ROs[p2];
                    ROs[p2] = tmp;
                }

                int idx = 0;
                foreach (var item in dogclsids.Where(d => d.Lho == dogCount.Lho ))
                {
                    _dogclasses.updateROs(item.DogClassId, ROs[idx++]);
                }
            }
        }
        public static void Split(int ClassId, int By)
        {
            string moduleSettings = ModuleConfig.GetSettings();
            Data.DogClasses dc = new Data.DogClasses(moduleSettings);
            List<DogClasses> dclist = new List<DogClasses>();

            DataSet ds = dc.getDogsInClass(ClassId);
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                dclist.Add(new DogClasses(row));
            }

            dclist = dclist.OrderBy(t => t.RO).ToList();
            int split = (int)Math.Truncate( (double)dclist.Count() / By);
            var remainder = dclist.Count() - (split * By );

            int splitLength = (int)split;
            ShowClasses showClass = new ShowClasses(ClassId);
            showClass.Part = 1;
            showClass.Update();
            var spt = splitLength;

            var j = Judge.getJudgeForClass(ClassId);
            var splitCnt = 2;
            for (var i = 1; i< By; i++)
            {
                if (i + 1 == By) { splitLength += remainder; }

                var copyid = showClass.copy(true);
                var splitClass = new ShowClasses(copyid);
                splitClass.ClassNo = showClass.ClassNo;
                splitClass.Position = showClass.Position;
                splitClass.RingID = showClass.RingID;
                splitClass.Part = splitCnt;
                splitClass.Update();
                ShowClasses.updateJudgeClasses(copyid, j.ID);

                for (int dogCnt = 0; dogCnt < splitLength; dogCnt++)
                {
                    var dogclass = dclist.ElementAt(  dogCnt + (int)spt);
                    dc.UpdateClassId(dogclass.ID, copyid);
                }
                spt += splitLength;
                splitCnt++;
            }
        }
        public static List<DogClassCount> GetEntryCountsByClassId(int ShowId, int ClassId)
        {
            String moduleSettings = ModuleConfig.GetSettings();
            Data.DogClasses dc = new Data.DogClasses(moduleSettings);

            DataSet ds = dc.getEntryCountsByClassNo(ShowId, ClassId);
            List<DogClassCount> dcCounts = new List<DogClassCount>();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                dcCounts.Add(new DogClassCount
                {
                    ClassId = Convert.ToInt32(row["ClassId"]),
                    Count = Convert.ToInt32(row["Count"]),
                    Part = Convert.ToInt32(row["Part"]),
                    Lho = Convert.ToInt32(row["Lho"])
                });
            }

            var cls = new ShowClasses(ClassId);
            if (cls.Lho > 0 && dcCounts.Count == 1 )
            {
                if (cls.Lho == 1 )
                {
                    dcCounts.Add(new DogClassCount
                    {
                        ClassId = ClassId,
                        Count = 0,
                        Part = 0,
                        Lho = 1
                    });
                }
                else if (cls.Lho == 2)
                {
                    dcCounts.Insert(0, new DogClassCount
                    {
                        ClassId = ClassId,
                        Count = 0,
                        Part = 0,
                        Lho = 1
                    });
                }
            }

            return dcCounts;
        }
        public void ProcessRequest(HttpContext context)
        {
            int ShowID = Convert.ToInt32(context.Request["showid"]);
            Shows show = new Shows(ShowID);

            String sortby = Convert.ToString(context.Request["sortby"]);

            Document doc = new Document(PageSize.A4, -50, -50, 2, 2);
            Stream output = new MemoryStream();
            var writer = PdfWriter.GetInstance(doc, output);
            StyleSheet sheet = new StyleSheet();

            doc.Open();

            PdfPTable ptable = new PdfPTable(1);
            PdfPCell cell;

            cell = new PdfPCell();
            cell.FixedHeight = 150;
            cell.BorderWidth = 0;
            ptable.AddCell(cell);

            cell = new PdfPCell(new Phrase(new Chunk("Master List", bigFont)));
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.BorderWidth = 0;
            cell.FixedHeight = 100;
            ptable.AddCell(cell);

            cell = new PdfPCell(new Phrase(new Chunk(show.ShowName, bigFont)));
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.BorderWidth = 0;
            ptable.AddCell(cell);

            cell = new PdfPCell(new Phrase(new Chunk(show.ShowDate.ToString("dd MMM yyyy"), bigFont)));
            cell.BorderWidth = 0;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            ptable.AddCell(cell);
            doc.Add(ptable);
            doc.NewPage();

            float[] colWidths = { 150, 65, 175, 200};
            int count = 0;
            String lastName = "";
            DataSet masterList = DogClasses.getMasterList(ShowID, sortby);
            String tmp = "";

            ptable = new PdfPTable(colWidths);
            cell = new PdfPCell(new Phrase(new Chunk("Handler Name", headerFont)));
            cell.BorderWidth = 0;
            ptable.AddCell(cell);

            cell = new PdfPCell(new Phrase("Ring No", headerFont));
            cell.BorderWidth = 0;
            ptable.AddCell(cell);

            cell = new PdfPCell(new Phrase("Dog Name", headerFont));
            cell.BorderWidth = 0;
            ptable.AddCell(cell);

            cell = new PdfPCell(new Phrase("Class Details", headerFont));
            cell.BorderWidth = 0;
            ptable.AddCell(cell);
            doc.Add(ptable);

            bool topBorder = false;
            Color altLine = new Color(224, 224, 224);

            List<Dogs> userDogs = null;
            foreach (DataRow row in masterList.Tables[0].Rows)
            {
                Color altColor = Color.WHITE;
                if (count % 2 == 0 )
                {
                    altColor = altLine;
                }

                MasterList masterListItem = new MasterList(row);
                ptable = new PdfPTable(colWidths);
                if (lastName == masterListItem.Name)
                {
                    cell = new PdfPCell(new Phrase(new Chunk("", normalFont)));
                    topBorder = false;
                }
                else
                {
                    if (userDogs != null)
                    {
                        altColor = (altColor == Color.WHITE ? altLine : Color.WHITE);

                        foreach (Dogs di in userDogs.Where(x => x.Status != -1).ToList())
                        {
                            List<DogClasses> dcList = DogClasses.Retrieve(di.ID, ShowID);
                            cell = new PdfPCell(new Phrase(new Chunk("", normalFont)));
                            cell.BorderWidth = 0;
                            cell.BackgroundColor = altColor;
                            ptable.AddCell(cell);
                            cell = new PdfPCell(new Phrase(new Chunk("", normalFont)));
                            cell.BorderWidth = 0;
                            cell.BackgroundColor = altColor;
                            ptable.AddCell(cell);
                            ptable.AddCell(AddDogDetails(di, dcList, altColor, false));
                            cell = new PdfPCell(new Phrase(new Chunk("", normalFont)));
                            cell.BorderWidth = 0;
                            cell.BackgroundColor = altColor;
                            ptable.AddCell(cell);
                            count++;
                            altColor = (count % 2 == 0 ? altLine : Color.WHITE);
                        }
                        count++;
                    }

                    topBorder = true;
                    tmp = masterListItem.Name;
                    //if (masterListItem.AltHandler > 0)
                    //{
                    //    User u = new User(masterListItem.AltHandler);
                    //    tmp = u.Name;
                    //}
                    var adminInd = "";
                    var us = new UserShows(masterListItem.UserId, ShowID);
                    var trans = Transaction.GetTransactionForShowUser(us.ID);
                    if (trans.Any() && trans.FirstOrDefault().EnteredBy == (int) Transaction.ENTERED_BY.SHOW_ADMIN_ENTRY)
                    {
                        adminInd = "(A) ";
                    }

                    User u = new User(masterListItem.UserId);
                    userDogs = Dogs.GetAllDogsForHandler(masterListItem.UserId, show.ShowDate);
                    Paragraph para = new Paragraph();
                    para.Add(new Chunk(adminInd + tmp + Environment.NewLine, normalFont));
                    para.Add(new Chunk(u.Address + Environment.NewLine , normalFont));
                    para.Add(new Chunk(u.Postcode, normalFont));
                    para.Add(new Chunk(Environment.NewLine, normalFont));
                    if (!string.IsNullOrEmpty(u.EmailAddress))
                    {
                        para.Add(new Chunk("Email " + u.EmailAddress + Environment.NewLine, normalFont));
                    }
                    if (!string.IsNullOrEmpty(u.HomePhone))
                    {
                        para.Add(new Chunk("Home Phone " + u.HomePhone + Environment.NewLine, normalFont));
                    }
                    if (!string.IsNullOrEmpty(u.Mobile))
                    {
                        para.Add(new Chunk("Mobile Phone " + u.Mobile + Environment.NewLine, normalFont));
                    }

                    cell = new PdfPCell(para);
                    cell.BorderColorTop = Color.BLACK;
                    cell.BorderWidthTop = 1;

                }
                cell.BorderWidth = 0;
                cell.BackgroundColor = altColor;
                ptable.AddCell(cell);

                cell = new PdfPCell(new Phrase(new Chunk(masterListItem.RingNumber.ToString(), normalFont)));
                cell.BorderWidth = 0;
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.BackgroundColor = altColor;
                if (topBorder)
                {
                    cell.BorderColorTop = Color.BLACK;
                    cell.BorderWidthTop = 1;
                }
                ptable.AddCell(cell);
                var d = userDogs.FirstOrDefault(x => x.ID == masterListItem.DogID);
                if (d != null)
                {
                    List<DogClasses> dcList = DogClasses.Retrieve(masterListItem.DogID, ShowID);
                    ptable.AddCell(AddDogDetails(d, dcList, altColor, topBorder));
                    d.Status = -1;
                    PdfPTable classDetailsTbl = new PdfPTable(1);
                    var p = new Paragraph();
                    bool first = true;
                    int  champClass = -1;
                    foreach (DogClasses dc in dcList)
                    {
                        ShowClasses sc = new ShowClasses(dc.Classid);
                        if (!first)
                        {
                            p.Add(new Chunk(String.Format(",{0,3}:", sc.ClassNo), normalFont));
                        }
                        else
                        {
                            p.Add(new Chunk(String.Format("{0,3}:", sc.ClassNo), normalFont));
                        }
                        p.Add(new Chunk(String.Format("{0,3}", dc.RO), normalFontBold));
                        first = false;
                        if (sc.EntryType == (int)Fpp.Core.Enums.EntryTypes.Championship)
                        {
                            champClass = d.ID;
                        }
                    }
                    cell = new PdfPCell(p);
                    cell.BorderWidth = 0;
                    classDetailsTbl.AddCell(cell);
                    cell = new PdfPCell(classDetailsTbl);
                    cell.BorderWidth = 0;
                    cell.BackgroundColor = altColor;
                    if (topBorder)
                    {
                        cell.BorderColorTop = Color.BLACK;
                        cell.BorderWidthTop = 1;
                    }
                    ptable.AddCell(cell);

                    if (champClass > -1)
                    {
                        cell = new PdfPCell();
                        cell.BorderWidth = 0;
                        cell.BackgroundColor = altColor;
                        cell.Colspan = 2;
                        ptable.AddCell(cell);

                        p = new Paragraph();
                        var champWins = DogHistory.GetRecordedWins(champClass);
                        p.Add(new Phrase(new Chunk("Grade 6 Wins" + Environment.NewLine, normalFontBold) ));
                        foreach (var win in champWins)
                        {
                            p.Add(new Chunk(String.Format("{0:dd-MM-yyyy} {1} {2} {3} ", win.WinDate, win.ShowName, win.ClassWon, win.Comments) + Environment.NewLine, normalFont));
                        }
                        cell = new PdfPCell(p);
                        cell.Colspan = 2;
                        cell.FixedHeight = 100;
                        cell.BorderWidth = 0;
                        cell.BackgroundColor = altColor;
                        ptable.AddCell(cell);
                    }

                }
                else
                {

                }
                doc.Add(ptable);

                lastName = masterListItem.Name;

                count++;
                //if (count > 100 ) break;
            }

            doc.Close();

            context.Response.ClearContent();
            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("content-disposition", String.Format("inline;filename=MasterList.pdf"));
            context.Response.BinaryWrite((output as MemoryStream).ToArray());
        }
 private void ScoreBoardColumnHeaders(ShowClasses showClass, PdfPTable callingListTbl, List<CallingListDto> callingList, float[] colWidths)
 {
     if (TeamPairsManager.isMultiDog(showClass.EntryType))
     {
         callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk("RO", headerHFont))) { BorderWidth = 0 });
         callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk("Team Name", headerHFont)))
         {
             BorderWidth = 0,
             Colspan = 2
         });
     }
     else
     {
         if (showClass.Lho == 1 || showClass.Lho == 2)
         {
             if (callingList.Any())
             {
                 var item = callingList.First();
                 var cnt = callingList.Count(x => x.Lho == item.Lho);
                 var title = $"{(item.Lho == 0 ? "Full Height " : "Lower Height")} ({cnt})";
                 callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk(title, headerHFont)))
                 {
                     BorderWidth = 0,
                     Colspan = colWidths.Length,
                     BackgroundColor = Color.LIGHT_GRAY,
                     HorizontalAlignment = Element.ALIGN_CENTER,
                     FixedHeight = 20,
                     BorderColorBottom = Color.BLACK,
                     BorderWidthBottom = 2
                 });
             }
             else
             {
                 var title = $"Dont Know (9999)";
                 callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk(title, headerHFont)))
                 {
                     BorderWidth = 0,
                     Colspan = colWidths.Length,
                     BackgroundColor = Color.LIGHT_GRAY,
                     HorizontalAlignment = Element.ALIGN_CENTER,
                     FixedHeight = 20,
                     BorderColorBottom = Color.BLACK,
                     BorderWidthBottom = 2
                 });
             }
         }
         callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk("RO", headerHFont))) { BorderWidth = 0 });
         callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk("Ring No", headerHFont))) {BorderWidth = 0});
         callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk("Handler", headerHFont))) { BorderWidth = 0 });
         callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk("Dog Name", headerHFont))) { BorderWidth = 0 });
     }
     callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk("Clears", headerHFont))) { BorderWidth = 0 });
     callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk("Faults", headerHFont))) { BorderWidth = 0 });
     callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk("Time", headerHFont))) { BorderWidth = 0 });
 }
        public static void CreateChampClasses(IEnumerable<ShowClasses> champClasses)
        {
            foreach (var champ in champClasses.ToList())
            {
                ShowClasses showClass = new ShowClasses(champ.ID);
                var baseName = (string.IsNullOrEmpty( showClass.ClassName ) ? "" :  showClass.ClassName.Replace(" Agility",""));
                showClass.ClassName = baseName + " Agility";
                showClass.Update();
                var newClsId = showClass.copy(true);

                ShowClasses newCls = new ShowClasses(newClsId);
                newCls.Part = showClass.Part + 1;
                newCls.ClassName = baseName + " Jumping";
                newCls.Update();
                DogClasses.CopyDogs(showClass.ID, newClsId);

                newClsId = newCls.copy(true);
                ShowClasses final = new ShowClasses(newClsId);
                final.Part = newCls.Part + 1;
                final.ClassName = baseName + " Final";
                final.Update();
                DogClasses.CopyDogs(showClass.ID, newClsId, 20, true);
            }
        }
        private void TeamScoreBoard(List<MultiDogEntry> multiTeams, ShowClasses showClass, PdfPTable callingListTbl)
        {
            var teamsForClass = multiTeams.Where(t => t.ClassId == showClass.ID).OrderBy(t => t.RO);
            var teamCnt = 0;
            foreach (var team in teamsForClass)
            {
                var altColor = (teamCnt%2 == 0 ? Color.WHITE : Color.LIGHT_GRAY);
                callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk(team.RO.ToString(), _normal10Black)))
                {
                    BorderWidth = 0,
                    FixedHeight = 20f
                });

                if (TeamPairsManager.isTeam(showClass.EntryType))
                {
                    callingListTbl.AddCell(new PdfPCell(
                            new Phrase(new Chunk(team.TeamDetails.TeamName.Replace("&#39;", "'"), _normal10Black)))
                    {
                        Colspan = 2,
                        BackgroundColor = altColor,
                        BorderWidth = 0
                    });
                }
                else
                {
                    var dogCnt = 0;
                    var handlerPara = new Paragraph();
                    var dogPara = new Paragraph();
                    foreach (var member in team.Members)
                    {
                        if (dogCnt < team.DogCount)
                        {
                            if (dogCnt > 0)
                            {
                                handlerPara.Add(new Phrase(Chunk.NEWLINE));
                                dogPara.Add(new Phrase(Chunk.NEWLINE));
                            }

                            handlerPara.Add(new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(member.HandlerName), _normal10Black)));
                            dogPara.Add(new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(member.DogName), _normal10Black)));
                        }
                        dogCnt++;
                    }
                    callingListTbl.AddCell(new PdfPCell(handlerPara)
                    {
                        BackgroundColor = altColor,
                        BorderWidth = 0,
                        BorderWidthTop = 0
                    });
                    callingListTbl.AddCell(new PdfPCell(dogPara)
                    {
                        BackgroundColor = altColor,
                        BorderWidth = 0,
                        BorderWidthTop = 0
                    });
                }

                callingListTbl.AddCell(new PdfPCell(new Phrase(""))
                {
                    BorderWidth = 1,
                    BorderWidthRight = 0,
                    BorderWidthTop = (teamCnt > 0 ? 0 : 1)
                });

                callingListTbl.AddCell(new PdfPCell(new Phrase(""))
                {
                    BackgroundColor = Color.WHITE,
                    BorderWidth = 1,
                    BorderWidthRight = 0,
                    BorderWidthTop = (teamCnt > 0 ? 0 : 1)
                });

                callingListTbl.AddCell(new PdfPCell(new Phrase(""))
                {
                    BackgroundColor = Color.WHITE,
                    BorderWidth = 1,
                    BorderWidthRight = 1,
                    BorderWidthTop = (teamCnt > 0 ? 0 : 1)
                });

                teamCnt++;
            }
        }
 public void BulkCopy(int ShowID, int showDetailsID, int newShowDetailsID, 
     List<Fpp.Core.Models.CopyValue> ShowChargeMap,
     List<Fpp.Core.Models.CopyValue> ClassTypesMap,
     int NewShowId = -1
     )
 {
     _showClasses.BulkCopy(showDetailsID, newShowDetailsID);
     int clsNo = 1;
     if (NewShowId > -1)
     {
         clsNo = _showClasses.getMaxClassNo(NewShowId) + 1;
     }
     DataSet ds = _showClasses.GetClassesFromShowDetails(newShowDetailsID);
     foreach (DataRow row in ds.Tables[0].Rows)
     {
         ShowClasses sc = new ShowClasses(row);
         if (ShowChargeMap != null)
         {
             var t = ClassTypesMap.Where(x => x.oldValue == sc.ClassType);
             if (t != null && t.Count() > 0)
             {
                 sc.ClassType = t.First().newValue;
             }
         }
         sc.Update();
     }
 }
        private void TrailerSheetRing(Document doc, Shows show, ShowDetails showDetails, Rings ring, Judge judge, String ringTemplate, int lastRingNo)
        {
            var trailerColumns = new float[] { 30, 150, 15, 35, 40, 20, 20, 20, 10 };
            var cellHeight = 18;
            var ptable = new PdfPTable(trailerColumns);

            AddCellToHeader(ptable, string.Format("Ring {0}", ring.RingNo));
            AddCellToHeader(ptable, string.Format("{0}", judge.Name));
            AddCellToHeader(ptable, "");
            AddCellToHeader(ptable, "Walking");
            AddCellToHeader(ptable, "Calling up to");
            AddCellToHeader(ptable, "End");
            AddCellToHeader(ptable, "Final");
            AddCellToHeader(ptable, "Closed");
            AddCellToHeader(ptable, "P");
            doc.Add(ptable);
            ptable = new PdfPTable(trailerColumns);

            DataSet classesDS = Rings.GetClassesForRing(ring.ID);
            classesDS = judge.getClassesForJudge();
            var ringTotal = 0;
            PdfPCell cell;
            var altRow = Color.LIGHT_GRAY;
            var topBorderColor = altRow;
            if (classesDS.Tables.Count > 0)
            {
                foreach (DataRow classRow in classesDS.Tables[0].Rows)
                {
                    var cls = new ShowClasses(Convert.ToInt32(classRow["ClassId"]));
                    altRow = altRow == Color.WHITE ? Color.LIGHT_GRAY : Color.WHITE;
                    topBorderColor = Color.BLACK;
                    var part = Convert.ToInt32(classRow["Part"]);
                    cell = new PdfPCell(new Phrase(new Chunk(
                            string.Format("Class {0}", classRow["ClsNo"]), headerHFont)));
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    cell.BackgroundColor = altRow;
                    ptable.AddCell(cell);

                    var lhoTableInd = new PdfPTable(1);

                    int clsHeight = Convert.ToInt32(classRow["Height"]);
                    var className = "";
                    if (clsHeight == 0)
                    {
                        className = string.Format("{0} {1} {2}{3}", classRow["LongName"], classRow["Name"],
                                                         ShowClasses.shortenGrades(classRow)
                                                         , (part > 0 ? " - Pt " + part : ""));
                    }
                    else
                    {
                        className = string.Format("{0} {1} {2} {3} {4}{5}", ShowClasses.expandHeight(classRow),
                                                        ShowClasses.expandCatagory(classRow),
                                                         classRow["LongName"], classRow["Name"],
                                                         ShowClasses.shortenGrades(classRow), (part > 0 ? " - Pt " + part : ""));
                    }

                    if (cls.Lho == 1 || cls.Lho == 2  )
                    {
                        var dcCounts = DogClasses.GetEntryCountsByClassId(show.ID, cls.ID);

                        var innerTable = new PdfPTable(1);
                        var classNameTable = new PdfPTable(2);
                        className = className.Replace("sponsored by", "sp by");
                        classNameTable.AddCell(new PdfPCell(new Phrase(new Chunk(className, headerHFont)))
                        {
                            HorizontalAlignment = Element.ALIGN_LEFT,
                            BackgroundColor = altRow,
                            NoWrap = true,
                            BorderWidth = 0,
                        });
                        classNameTable.AddCell(new PdfPCell(new Phrase(new Chunk(dcCounts[0].Lho == 0 ? "Full Height" : "Lower Height", headerHFont)))
                        {
                            HorizontalAlignment = Element.ALIGN_RIGHT,
                            BackgroundColor = altRow,
                            NoWrap = true,
                            BorderWidth = 0,
                        });
                        innerTable.AddCell(new PdfPCell(classNameTable)
                        {
                            BackgroundColor = altRow,
                            NoWrap = false,
                            BorderWidth = 0,
                            BorderColorBottom = Color.GRAY,
                            BorderWidthBottom = 1
                        });

                        innerTable.AddCell(new PdfPCell(new Phrase(new Chunk((dcCounts[1].Lho == 0 ? "Full Height" : "Lower Height"), headerHFont)))
                        {
                            HorizontalAlignment = Element.ALIGN_RIGHT,
                            PaddingRight = 5,
                            BackgroundColor = altRow,
                            NoWrap = false,
                            BorderWidth = 0,
                        });
                        ptable.AddCell(new PdfPCell(innerTable) { });

                        innerTable = new PdfPTable(1);
                        foreach (var dcc in dcCounts)
                        {
                            innerTable.AddCell(new PdfPCell(new Phrase(new Chunk(string.Format("{0}", dcc.Count), headerHFont)))
                            {
                                HorizontalAlignment = Element.ALIGN_RIGHT,
                                BackgroundColor = altRow,
                                NoWrap = false,
                                BorderWidth = 0,
                                BorderWidthBottom = 1,
                                BorderColorBottom = Color.GRAY
                            });

                        }
                        ptable.AddCell(new PdfPCell(innerTable) { HorizontalAlignment = Element.ALIGN_RIGHT});

                        lhoTableInd.AddCell(new PdfPCell(new Phrase("  ")) { BorderWidth = 0, BorderWidthBottom = 1, BorderColorBottom = Color.GRAY });
                        lhoTableInd.AddCell(new PdfPCell(new Phrase("  ")) { BorderWidth = 0});
                    }
                    else
                    {
                        ptable.AddCell(new PdfPCell(new Phrase(new Chunk(className, headerHFont)))
                        {
                            HorizontalAlignment = Element.ALIGN_LEFT,
                            BackgroundColor = altRow,
                            NoWrap = false
                        });

                        var classTotal = Fpp.Core.Utils.CalcDogsInCalc(classRow);
                        ringTotal += classTotal;
                        cell = new PdfPCell(new Phrase(new Chunk(string.Format("{0, 5}", classTotal), headerHFont)));
                        cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        cell.BackgroundColor = altRow;
                        ptable.AddCell(cell);
                    }

                    ptable.AddCell(new PdfPCell(lhoTableInd) { BackgroundColor = altRow });
                    ptable.AddCell(new PdfPCell(lhoTableInd) { BackgroundColor = altRow });
                    ptable.AddCell(new PdfPCell(lhoTableInd) { BackgroundColor = altRow });
                    ptable.AddCell(new PdfPCell(lhoTableInd) { BackgroundColor = altRow });
                    ptable.AddCell(new PdfPCell(lhoTableInd) { BackgroundColor = altRow });
                    ptable.AddCell(new PdfPCell(lhoTableInd) { BackgroundColor = altRow });
                }
                cell = new PdfPCell(new Phrase(new Chunk("", headerHFont)));
                cell.FixedHeight = cellHeight;
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                cell = new PdfPCell(new Phrase(new Chunk(string.Format("{0}",ringTotal), headerHFont)));
                cell.FixedHeight = cellHeight;
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                ptable.AddCell(cell);
                cell = new PdfPCell(new Phrase(new Chunk("", headerHFont)));
                cell.FixedHeight = cellHeight;
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                ptable.AddCell(cell);

                cell = new PdfPCell(new Phrase(new Chunk("", headerHFont)));
                cell.FixedHeight = cellHeight;
                cell.BorderWidth = 0;
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                ptable.AddCell(cell);

                doc.Add(ptable);

            }
        }
 public void updatePosition(String[] posList)
 {
     for (int i = 0; i < posList.Length; i++)
     {
         int id = Convert.ToInt32(posList[i]);
         ShowClasses sc = new ShowClasses(id);
         sc.Position = i;
         sc.Update();
     }
 }
        public int CallingSheets(Document doc, int showId, int ringId, PdfWriter writer, int position = -1)
        {
            doc.Open();
            var font = new Font(Font.COURIER, 10, Font.NORMAL, Color.BLACK);
            var fontBold = new Font(Font.COURIER, 10, Font.BOLD, Color.BLACK);
            var sc = new ShowClasses();
            var currentRing = new Rings(ringId);
            var showClasses = ShowClasses.GetAllClassesForShowRing(showId, ringId, position);
            var ret = showClasses.Count;
            float[] colWidthsStandard = { 35, 35, 50, 200, 200 };
            float[] colWidthsTeam = { 35, 200, 200 };
            PdfPTable callingListTbl = null;
            var currentClassNo = 0;
            var multiClasses = TeamPairsManager.GetTeamPairClasses(showId);
            var multiTeams = TeamPairsManager.GetTeamPairsForShow(showId, multiClasses);
            foreach (var showClass in showClasses)
            {
                var colWidths = (TeamPairsManager.isMultiDog(showClass.EntryType) ? colWidthsTeam : colWidthsStandard);
                if (currentClassNo != showClass.ClassNo)
                {
                    if (currentClassNo != 0)
                    {

                    }
                    callingListTbl =
                        new PdfPTable(colWidths)
                        {
                            HeaderRows = 2
                        };
                }
                string tmp;
                if (TeamPairsManager.isMultiDog(showClass.EntryType) || showClass.EntryType == 10)
                {
                    tmp =
                        $"Ring No:{currentRing.RingNo}   Class No:{showClass.ClassNo} {showClass.longHeight} {showClass.LongClassName} {showClass.ClassName}";
                }
                else
                {
                    //                    tmp = String.Format("Ring No:{5}   Class No:{0} {1} {2} {3} {6} {7} {4}", showClass.ClassNo, showClass.longHeight, showClass.longCatagory, showClass.LongClassName, grades, currentRing.RingNo, showClass.ClassName, (showClass.Part > 0 ? "Part " + showClass.Part : ""));
                    tmp = $"Ring No:{currentRing.RingNo}   Class No:{showClass.NormalName()}";
                    tmp += $" {(showClass.Part > 0 ? "Part " + showClass.Part : "")}";
                }
                var cell = new PdfPCell(new Phrase(new Chunk(tmp, ClassTitleFont)))
                {
                    Colspan = colWidths.Length,
                    BorderWidth = 0,
                    FixedHeight = 40F
                };
                callingListTbl.AddCell(cell);

                cell = new PdfPCell(new Phrase(new Chunk("", ClassTitleFont)))
                {
                    Colspan = colWidths.Length,
                    BorderWidth = 0
                };
                callingListTbl.AddCell(cell);
                doc.Add(callingListTbl);
                callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk("RO", headerFont))) { BorderWidth = 0, HorizontalAlignment = Element.ALIGN_RIGHT});

                if (!TeamPairsManager.isMultiDog(showClass.EntryType))
                {
                    callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk(" ", headerFont))) { BorderWidth = 0 });
                    callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk("Ring No", headerFont))) { BorderWidth = 0, HorizontalAlignment =  Element.ALIGN_RIGHT});
                }
                callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk("Handler", headerFont))) { BorderWidth = 0 });
                callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk("Dog Name", headerFont))) { BorderWidth = 0 });
                doc.Add(callingListTbl);
                int altFlag = 0;
                Color altLine = Color.LIGHT_GRAY;
                callingListTbl = new PdfPTable((TeamPairsManager.isMultiDog(showClass.EntryType) ? colWidthsTeam : colWidths));
                if (TeamPairsManager.isMultiDog(showClass.EntryType))
                {
                    var teamsForClass = multiTeams.Where(t => t.ClassId == showClass.ID).OrderBy(t => t.RO);

                    foreach (var team in teamsForClass)
                    {
                        var altColor = Color.WHITE;
                        if (altFlag % 2 == 0 && showClass.EntryType != 5)
                        {
                            altColor = altLine;
                        }

                        cell = new PdfPCell(new Phrase(new Chunk(team.RO.ToString(), headerHFont)))
                        {
                            BorderWidth = 0,
                            BackgroundColor = altColor
                        };
                        callingListTbl.AddCell(cell);

                        if (TeamPairsManager.isTeam(showClass.EntryType))
                        {
                            cell =
                                new PdfPCell(
                                    new Phrase(new Chunk("Team Name:" + team.TeamDetails.TeamName.Replace("&#39;", "'"),
                                        headerHFont)))
                                {
                                    BackgroundColor = altColor,
                                    BorderWidth = 0
                                };
                            callingListTbl.AddCell(cell);

                            cell =
                                new PdfPCell(
                                    new Phrase(new Chunk("Captain:" + team.TeamDetails.Captain.Replace("&#39;", "'"),
                                        headerHFont)))
                                {
                                    BackgroundColor = altColor,
                                    BorderWidth = 0
                                };
                            callingListTbl.AddCell(cell);

                            cell = new PdfPCell(new Phrase(new Chunk("", headerHFont)))
                            {
                                BackgroundColor = altColor,
                                BorderWidth = 0
                            };
                            callingListTbl.AddCell(cell);
                        }

                        var dogCnt = 0;
                        var handlerPara = new Paragraph();
                        var dogPara = new Paragraph();
                        foreach (var member in team.Members)
                        {
                            if (dogCnt < team.DogCount)
                            {
                                if (dogCnt > 0)
                                {
                                    handlerPara.Add(new Phrase(Chunk.NEWLINE));
                                    dogPara.Add(new Phrase(Chunk.NEWLINE));
                                }

                                handlerPara.Add(new Phrase(new Chunk(Utils.TitleCaseString(member.HandlerName).Replace("&#39;", "'"), font)));
                                dogPara.Add(new Phrase(new Chunk(Utils.TitleCaseString(member.DogName).Replace("&#39;", "'"), font)));
                            }
                            dogCnt++;
                        }
                        cell = new PdfPCell(handlerPara)
                        {
                            BorderWidth = 0,
                            BorderWidthTop = 0,
                            BackgroundColor = altColor
                        };
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(dogPara)
                        {
                            BorderWidth = 0,
                            BorderWidthTop = 0,
                            BackgroundColor = altColor
                        };
                        callingListTbl.AddCell(cell);
                        doc.Add(callingListTbl);

                        altFlag++;
                        callingListTbl = new PdfPTable((TeamPairsManager.isMultiDog(showClass.EntryType) ? colWidthsTeam : colWidths));

                        var lineLeft = writer.GetVerticalPosition(false) - doc.BottomMargin;
                        if (lineLeft < 50)
                        {
                            doc.NewPage();
                        }
                    }
                }
                else
                {
                    var callingList = sc.GetCallingList(showId, showClass.ID);
                    foreach (var item in callingList)
                    {

                        Color altColor = Color.WHITE;
                        if (altFlag % 2 == 0 && showClass.EntryType != 5)
                        {
                            altColor = altLine;
                        }

                        callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk($"{item.Ro}", font)))
                        {
                            BorderWidth = 0,
                            BackgroundColor = altColor,
                            HorizontalAlignment = Element.ALIGN_RIGHT
                        });

                        var borderWidth = 0;
                        callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk(item.Lho == 0 ? "" : "LHO", font)))
                        {
                            HorizontalAlignment = Element.ALIGN_RIGHT,
                            BackgroundColor = altColor,
                            BorderWidth = borderWidth
                        });
                        callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk($"{item.RingNumber}", font)))
                        {
                            HorizontalAlignment = Element.ALIGN_CENTER,
                            BackgroundColor = altColor,
                            BorderWidth = borderWidth
                        });

                        var handlerName = Utils.TitleCaseString(item.Name);
                        User user;
                        var namePhrase = new Phrase();
                        var us = new UserShows(item.UserId, showId);
                        if (item.DefaultHandlerId > 0)
                        {
                            user = new User(item.DefaultHandlerId);
                            handlerName = user.Name;
                        }
                        if (item.AltHandlerId > 0)
                        {
                            user = new User(item.AltHandlerId);
                            handlerName = user.Name;
                        }

                        if (us.HandlerType == (int)Core.Enums.DiscountTypes.Member)
                        {
                            namePhrase.Add(new Chunk("(M)", fontBold));
                            namePhrase.Add(new Chunk(Utils.TitleCaseString(handlerName), fontBold));
                        }
                        else
                        {
                            namePhrase.Add(new Chunk(Utils.TitleCaseString(handlerName), font));
                        }
                        cell = new PdfPCell(namePhrase)
                        {
                            BackgroundColor = altColor,
                            BorderWidth = borderWidth
                        };
                        callingListTbl.AddCell(cell);

                        cell =
                            new PdfPCell(
                                new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(item.KcName), font)))
                            {
                                BackgroundColor = altColor,
                                BorderWidth = borderWidth
                            };
                        callingListTbl.AddCell(cell);

                        altFlag++;
                    }
                    doc.Add(callingListTbl);
                }
                doc.NewPage();
            }
            return ret;
        }
        private void printRingForUser(UserShows userShow, int UserID, Document doc, ref List<int> defaultUsers, ref int pageCount)
        {
            float[] ringColumns = new float[] { 300, 300, 300, 300 };

            User currentUser = new User(userShow.Userid);
            Shows show = new Shows(userShow.ShowID);

            List<ShowDetails> showDetailsList = ShowDetails.GetShowDetails(userShow.ShowID);

            Rings r = new Rings();
            DataSet ringList = r.GetAllRingsForShow(userShow.ShowID, "ShowDate");

            Dogs d = new Dogs();

            DogClasses dc = new DogClasses();
            DateTime dt = DateTime.Now;
            string currentJudge = "";
            int currentRingID = 0;
            int ShowDetailsID = -1;
            int PrevShowDetailsID = -1;
            PdfPTable rings = new PdfPTable(ringColumns);

            int ringCnt = 0;
            PdfPCell cell = null;
            PdfPTable ringDetails = null;
            PdfPTable classDetailsTable = null;
            List<int> dogsRunningToday = new List<int>();
            PdfPTable headerPage = null;
            List<TeamPairsTrioDto> pairsTeams = new List<TeamPairsTrioDto>();
            try
            {
                foreach (DataRow ringRow in ringList.Tables[0].Rows)
                {
                    Rings ring = new Rings(ringRow);
                    int RingID = Convert.ToInt32(ringRow["RingID"]);
                    int EntryType = Convert.ToInt32(ringRow["EntryType"]);
                    int Lho = Convert.ToInt32(ringRow["Lho"]);
                    ShowDetailsID = Convert.ToInt32(ringRow["ShowDetailsID"]);

                    if (ringRow.IsNull("ClassID"))
                    {
                        continue;
                    }
                    int ClassID = Convert.ToInt32(ringRow["ClassID"]);
                    int ClassNo = Convert.ToInt32(ringRow["ClsNo"]);
                    DateTime rowDT = Convert.ToDateTime(ringRow["ShowDate"]);
                    if (rowDT != dt)
                    {
                        if (currentRingID != 0)
                        {
                            if (ringCnt % MaxColumns != 0)
                            {
                                var remind = ringCnt % MaxColumns;
                                while (remind-- > 0)
                                {
                                    cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                                    cell.BorderWidth = 0;
                                    rings.AddCell(cell);
                                }
                            }
                            if (dogsRunningToday.Count() > 0 || UserID == -1)
                            {
                                doc.Add(headerPage);
                                doc.Add(rings);
                                if (UserID > -1)
                                {
                                    if (currentUser.UserID != UserID)
                                    {
                                        User defaultHandler = new User(UserID);
                                    }
                                }

                                doc.NewPage();
                                pageCount++;
                            }
                        }

                        dogsRunningToday.Clear();
                        if (UserID > -1)
                        {
                            if (currentUser.UserID == UserID)
                            {
                                headerPage = DrawHeader(show, rowDT, currentUser, userShow);
                            }
                            else
                            {
                                User defaultHandler = new User(UserID);
                                headerPage = DrawHeader(show, rowDT, defaultHandler, userShow);
                            }
                        }
                        else
                        {
                            headerPage = DrawHeader(show, rowDT, null, null);

                        }
                        dt = rowDT;
                        rings = new PdfPTable(ringColumns);
                        rings.WidthPercentage = 100;
                        ringCnt = 0;
                    }

                    if (currentRingID != RingID)
                    {
                        currentJudge = "";
                        ringCnt++;
                        ringDetails = new PdfPTable(1);
                        rings.AddCell(new PdfPCell(ringDetails));

                        //List<Judge> judgeList = Judge.getJudgesForRingList(RingID);
                        string JudgeName = Judge.getJudgeForClass(ClassID).Name;
                        int ClsCount = DogClasses.GetDogsInRing(RingID);

                        cell = new PdfPCell(new Phrase(new Chunk(string.Format("Ring No {0} ({1})", ringRow["RingNo"].ToString(), ClsCount), judgeFont)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        ringDetails.AddCell(cell);

                        if (currentJudge != JudgeName)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(JudgeName), judgeFont)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            ringDetails.AddCell(cell);
                            currentJudge = JudgeName;
                        }
                        currentRingID = RingID;
                        classDetailsTable = new PdfPTable(DetailsColWidths);
                        classDetailsTable.DefaultCell.BorderWidth = 0;
                        ringDetails.AddCell(classDetailsTable);
                    }
                    else
                    {
                        string JudgeName = Judge.getJudgeForClass(ClassID).Name;
                        if (currentJudge != JudgeName)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk("  ", judgeFont)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            ringDetails.AddCell(cell);
                            cell = new PdfPCell(new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(JudgeName), judgeFont)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            ringDetails.AddCell(cell);

                            classDetailsTable = new PdfPTable(DetailsColWidths);
                            classDetailsTable.DefaultCell.BorderWidth = 0;
                            ringDetails.AddCell(classDetailsTable);
                            currentJudge = JudgeName;
                        }
                    }
                    DataSet dogsList = d.GetDogsInClass(userShow.Userid, ClassID);
                    int dogsInClass = d.dogsInClassCount(ClassID);
                    List<DogClassCount> dcCounts = DogClasses.GetEntryCountsByClassId(userShow.ShowID, ClassID);

                    String clsName;
                    var part = Convert.ToInt32(ringRow["Part"]);
                    var lhoInd = "";
                    var dogsInClassDisplay = "";
                    if (dcCounts.Count > 1)
                    {
                        if (Lho == 1) {
                            dogsInClassDisplay = String.Format("({0}/{1})", dcCounts[0].Count, dcCounts[1].Count);
                        }
                        else
                        {
                            dogsInClassDisplay = String.Format("({0}/{1})", dcCounts[1].Count, dcCounts[0].Count);
                        }
                    }
                    else
                    {
                        dogsInClassDisplay = String.Format("({0})", dogsInClass);
                    }

                    if (Lho == 1)
                    {
                        lhoInd = "(FH 1st)";
                    }
                    else if (Lho == 2)
                    {
                        lhoInd = "(LHO 1st)";
                    }
                    if (EntryType != 10)
                    {
                        clsName = new ShowClasses(ClassID).NormalName(withClassNo:false, useAbbrFlag:true);
                    }
                    else
                    {
                        clsName = String.Format("{0} {1} {2} ",
                                        ShowClasses.expandHeight(ringRow),
                                        ringRow["LongName"].ToString().Trim(),
                                        ringRow["name"].ToString().Trim());
                    }
                    clsName = clsName.Replace("(Special Class", "S");
                    clsName = clsName.Replace("(Money Class", "Money");
                    clsName = clsName.Replace("First Place Processing", "FPP");
                    clsName = clsName.Replace("First Contact", "FC");
                    clsName = clsName.Replace("Qualifier", "Q");

                    if (part > 0 && EntryType != 10)
                    {
                        clsName += "Pt " + part;
                    }

                    if (dogsList.Tables[0].Rows.Count > 0)
                    {
                        /*
                        Combined 1-7 All Allsorts Agility sponsored by paws for a walk
                        Combined 6-7 Medium Agility

                            * */
                        var WrapClassDescription = clsName.Length > 45;
                        Phrase[] tmpCells = new Phrase[3];
                        tmpCells[0] = new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogInClass));
                        tmpCells[1] = new Phrase(new Chunk(clsName, dogInClass));
                        tmpCells[2] = new Phrase(new Chunk(dogsInClassDisplay, dogNotInClass ));

                        int countDogs = 0;
                        int DefaultHandler;

                        Paragraph p = new Paragraph();
                        List<Paragraph> allDogsInClass = new List<Paragraph>();
                        foreach (DataRow dogRow in dogsList.Tables[0].Rows)
                        {
                            var dogLho = Convert.ToInt32(dogRow["Lho"]);
                            int DogID = Convert.ToInt32(dogRow["DogID"]);
                            DefaultHandler = Convert.ToInt32(dogRow["DefaultHandler"]);
                            if (DefaultHandler == 0) DefaultHandler = -1;
                            if ((DefaultHandler == -1 && currentUser.UserID == UserID) ||
                                (DefaultHandler == UserID)
                                )
                            {
                                if (countDogs == 0)
                                {
                                    cell = new PdfPCell(tmpCells[0]);
                                    cell.BorderWidth = 0;
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                    classDetailsTable.AddCell(cell);
                                    var namePara = new Paragraph();
                                    namePara.Add(tmpCells[1]);
                                    namePara.Add(new Phrase(new Chunk(lhoInd, lhoFontBold)));
                                    p.Add(namePara);
                                }
                                if (!dogsRunningToday.Contains(DogID))
                                {
                                    dogsRunningToday.Add(DogID);
                                }
                                String dogName = dogRow["DogName"].ToString();
                                if (dogName.Length == 0)
                                {
                                    dogName = dogRow["KCName"].ToString();
                                }
                                var chunk = new Chunk("   ", dogDetailsInClass);
                                chunk.SetBackground(new Color(System.Drawing.ColorTranslator.FromHtml(dogRow["DogColour"].ToString())));

                                var dogPara = new Paragraph();
                                dogPara.Add(new Phrase(chunk));

                                if (TeamPairsManager.isMultiDog( EntryType ))
                                {
                                    pairsTeams.Add(new TeamPairsTrioDto
                                    {
                                        ClassId = ClassID,
                                        ClassNo = ClassNo,
                                        DogId = DogID,
                                        DogName = dogName,
                                        RO = -1
                                    });
                                }
                                dogPara.Add(new Phrase(new Chunk(String.Format(" [{1}] {0}", Fpp.Core.Utils.TitleCaseString(dogName), dogRow["RO"]), dogDetailsInClass)));
                                dogPara.Add(new Phrase(new Chunk(String.Format("{0}", (dogLho == 0 ? "" : " (LHO)")), font8)));
                                dogPara.Add(Chunk.NEWLINE);

                                int AltHandler = Convert.ToInt32(dogRow["AltHandler"]);
                                String HandlerName = "";
                                if (AltHandler > 0)
                                {
                                    User u = new User(AltHandler);
                                    HandlerName = u.Name;
                                    dogPara.Add(new Phrase(new Chunk(String.Format("Handler:{0}", Fpp.Core.Utils.TitleCaseString(HandlerName)), dogInClass)));
                                }
                                allDogsInClass.Add(dogPara);
                                countDogs++;
                            }
                            else
                            {
                                if (defaultUsers != null && defaultUsers.IndexOf(DefaultHandler) == -1)
                                {
                                    defaultUsers.Add(DefaultHandler);
                                }
                            }
                        }
                        if (countDogs == 0)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogNotInClass)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            classDetailsTable.AddCell(cell);

                            var namePara = new Paragraph();
                            namePara.Add(new Phrase(new Chunk(clsName, dogNotInClass)));
                            namePara.Add(new Phrase(new Chunk(lhoInd, lhoFontBold)));
                            p.Add(namePara);
                            cell = new PdfPCell(p);
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cell.NoWrap = false;
                            classDetailsTable.AddCell(cell);

                            cell = new PdfPCell(new Phrase(new Chunk(dogsInClassDisplay, dogNotInClass)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            classDetailsTable.AddCell(cell);
                        }
                        else
                        {

                            cell = new PdfPCell(p);
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cell.NoWrap = false;

                            classDetailsTable.AddCell(cell);

                            cell = new PdfPCell(tmpCells[2]);
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            classDetailsTable.AddCell(cell);

                            cell = new PdfPCell(new Phrase(new Chunk("", dogDetailsInClass)));
                            cell.BorderWidth = 0;
                            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cell.NoWrap = false;
                            classDetailsTable.AddCell(cell);

                            var tbl4Dogs = new PdfPTable(1);
                            foreach (var item in allDogsInClass)
                            {
                                cell = new PdfPCell(new Phrase(item));
                                cell.BorderWidth = 0;
                                cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                                tbl4Dogs.AddCell(cell);
                            }
                            cell = new PdfPCell();
                            cell.BorderWidth = 0;
                            cell.FixedHeight = 4f;
                            tbl4Dogs.AddCell(cell);

                            cell = new PdfPCell(tbl4Dogs);
                            cell.BorderWidth = 0;
                            cell.Colspan = 2;
                            classDetailsTable.AddCell(cell);
                        }
                    }
                    else
                    {
                        cell = new PdfPCell(new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);

                        var namePara = new Paragraph();
                        namePara.Add(new Phrase(new Chunk(clsName, dogNotInClass)));
                        namePara.Add(new Phrase(new Chunk(lhoInd, lhoFontBold)));
                        cell = new PdfPCell(namePara);
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        cell.NoWrap = false;
                        classDetailsTable.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk(dogsInClassDisplay, dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);

                    }

                    PrevShowDetailsID = ShowDetailsID;
                }

                if (dogsRunningToday.Count() > 0 || UserID == -1)
                {
                    if (ringCnt % MaxColumns != 0)
                    {
                        var remind = ringCnt % MaxColumns;
                        while (remind-- > 0)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                            cell.BorderWidth = 0;
                            rings.AddCell(cell);
                        }
                        doc.Add(headerPage);
                        doc.Add(rings);
                    }

                    if (UserID > -1)
                    {
                        if (currentUser.UserID != UserID)
                        {
                            User defaultHandler = new User(UserID);
                        }
                    }
                    doc.NewPage();
                    pageCount++;
                }
                else
                {
                    if (dogsRunningToday.Count() > 0)
                    {
                        if (ringCnt % MaxColumns != 0)
                        {
                            var remind = ringCnt % MaxColumns;
                            while (remind-- > 0)
                            {
                                cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                                cell.BorderWidth = 0;
                                rings.AddCell(cell);
                            }
                            doc.Add(headerPage);
                            doc.Add(rings);
                        }

                        if (UserID > -1)
                        {
                            if (currentUser.UserID != UserID)
                            {
                                User defaultHandler = new User(UserID);
                            }
                        }
                        doc.NewPage();
                        pageCount++;
                    }
                }
            }
            catch (Exception e)
            {
                AppException.LogError($"Error Running Plan:{e.Message},{e.StackTrace}");
            }
        }
        public int ResultSheets(Document doc, int ShowID, int RingID, int Position , bool pagePerClass, PdfWriter writer )
        {
            int ret = 0;
            Font smallFont = new Font(Font.COURIER, 8, Font.NORMAL, Color.BLACK);
            Font normalFont = new Font(Font.COURIER, 10, Font.NORMAL, Color.BLACK);
            Font bigFont = new Font(Font.HELVETICA, 25, Font.NORMAL, Color.BLACK);
            Font mediumFont = new Font(Font.HELVETICA, 20, Font.NORMAL, Color.BLACK);
            ShowClasses sc = new ShowClasses();
            Rings currentRing = new Rings(RingID);
            List<ShowClasses> showClasses = ShowClasses.GetAllClassesForShowRing(ShowID, RingID, Position);
            var storedResults = Business.TrophiesRosettes.getTandRForShow(ShowID);
            var lineLeft = writer.GetVerticalPosition(false) - doc.BottomMargin;

            ret = showClasses.Count;
            PdfPTable callingListTbl = null;
            foreach (ShowClasses showClass in showClasses)
            {
                var resultCnts = storedResults.Where(x => x.ClsNo == showClass.ClassNo);

                int gradeidx = 0;
                foreach (var totals in resultCnts)
                {
                    PdfPTable ptable = new PdfPTable(3);
                    PdfPCell cell;

                    String grades;
                    String subTitle;

                    if (_writer != null)
                    {
                        _writer.GetVerticalPosition(false);
                    }

                    if (showClass.Catagory == 0)
                    {
                        if (gradeidx < showClass.Grades.Length)
                        {
                            grades = "Grade " + showClass.Grades[gradeidx];
                        }
                        else
                        {
                            grades = showClass.Grades;
                        }
                        subTitle = String.Format("{0} {1} {2} {3} {5}{6} Judge: {4}", showClass.longHeight, showClass.longCatagory, showClass.LongClassName, grades, Judge.getJudgeForClass(showClass.ID).JudgeName, showClass.ClassName, (showClass.Part > 0 ? "Part " + showClass.Part : ""));
                    }
                    else
                    {
                        if (showClass.Grades.Length == 1)
                        {
                            grades = showClass.Grades;
                        }
                        else
                        {
                            grades = showClass.Grades[0] + " - " + showClass.Grades[showClass.Grades.Length - 1];
                        }
                        subTitle = String.Format("{0} {1} Judge: {2}", showClass.NormalName(withClassNo:false), (showClass.Part > 0 ? "Part " + showClass.Part : ""), Judge.getJudgeForClass(showClass.ID).JudgeName);

                    }
                    String tmp = String.Format("Ring No:{0} - Result Sheet ", currentRing.RingNo);
                    cell = new PdfPCell(new Phrase(new Chunk(tmp, bigFont)));
                    cell.Colspan = 2;
                    cell.BorderWidth = 0;
                    ptable.AddCell(cell);

                    tmp = String.Format("Class No:{0}", showClass.ClassNo);
                    cell = new PdfPCell(new Phrase(new Chunk(tmp, bigFont)));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.BorderWidth = 2;
                    cell.Padding = 5;
                    ptable.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk(subTitle, mediumFont)));
                    cell.Colspan = 3;
                    cell.BorderWidth = 0;
                    ptable.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk("", ClassTitleFont)));
                    cell.Colspan = 3;
                    cell.BorderWidth = 0;
                    ptable.AddCell(cell);
                    ptable.AddCell(cell);
                    ptable.AddCell(cell);
                    doc.Add(ptable);
                    DrawCourseBoxes(doc);

                    float[] colWidths = { 75, 75, 200, 200, 50, 75 };
                    callingListTbl = new PdfPTable(colWidths);

                    cell = new PdfPCell(new Phrase(new Chunk("Place", headerHFont)));
                    cell.BorderWidth = 1;
                    cell.BorderWidthBottom = 0;
                    cell.FixedHeight = 35f;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    callingListTbl.AddCell(cell);

                    if (TeamPairsManager.isMultiDog(showClass.EntryType))
                    {
                        if (TeamPairsManager.isTeam(showClass.EntryType))
                        {
                            cell = new PdfPCell(new Phrase(new Chunk("Team Name", headerHFont)));
                        }
                        else
                        {
                            cell = new PdfPCell(new Phrase(new Chunk("Handler/Dog", headerHFont)));
                        }
                        cell.BorderWidth = 1;
                        cell.BorderWidthBottom = 0;
                        cell.Colspan = 3;
                        callingListTbl.AddCell(cell);
                    } else
                    {
                        cell = new PdfPCell(new Phrase(new Chunk("Ring Number", headerHFont)));
                        cell.BorderWidth = 1;
                        cell.BorderWidthBottom = 0;
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk("Handler", headerHFont)));
                        cell.BorderWidth = 1;
                        cell.BorderWidthBottom = 0;
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk("Dog Name", headerHFont)));
                        cell.BorderWidth = 1;
                        cell.BorderWidthBottom = 0;
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        callingListTbl.AddCell(cell);

                    }

                    cell = new PdfPCell(new Phrase(new Chunk("Clear/ Faults", headerHFont)));
                    cell.BorderWidth = 1;
                    cell.BorderWidthBottom = 0;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    callingListTbl.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk("Time", headerHFont)));
                    cell.BorderWidth = 1;
                    cell.BorderWidthBottom = 0;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    callingListTbl.AddCell(cell);

                    int maxRosettes = totals.Rosettes;// Utils.calcRosettes(dogCounts);
                    int maxTrophies = totals.Trophies; // Utils.calcTrophies(dogCounts);
                    float rowHeight = 25f;
                    if (TeamPairsManager.isMultiDog(showClass.EntryType)  )
                    {
                        rowHeight = (TeamPairsManager.isTeam(showClass.EntryType)) ? 120f : 65f;
                    }

                    for (int resultRow = 0; resultRow < maxRosettes; resultRow++)
                    {
                        int bwb = 0;
                        if (resultRow == maxRosettes - 1)
                        {
                            bwb = 1;
                        }
                        Color background = Color.WHITE;
                        if (maxTrophies > 0)
                        {
                            background = Color.LIGHT_GRAY;
                        }
                        maxTrophies--;
                        cell = new PdfPCell(new Phrase(new Chunk(calcPlace(resultRow + 1), normalFont)));
                        cell.BorderWidth = 1;
                        cell.BorderWidthBottom = bwb;
                        cell.FixedHeight = rowHeight;
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.BackgroundColor = background;
                        callingListTbl.AddCell(cell);

                        if (TeamPairsManager.isMultiDog(showClass.EntryType))
                        {
                            cell = new PdfPCell(new Phrase(new Chunk("", normalFont)));
                            cell.BorderWidth = 1;
                            cell.BackgroundColor = background;
                            cell.BorderWidthBottom = bwb;
                            cell.Colspan = 3;
                            callingListTbl.AddCell(cell);
                            cell = new PdfPCell(new Phrase(new Chunk("", normalFont)));
                            cell.BorderWidth = 1;
                            cell.BackgroundColor = background;
                            cell.BorderWidthBottom = bwb;
                            callingListTbl.AddCell(cell);
                            callingListTbl.AddCell(cell);

                        }
                        else
                        {
                            cell = new PdfPCell(new Phrase(new Chunk("", normalFont)));
                            cell.BorderWidth = 1;
                            cell.BackgroundColor = background;
                            cell.BorderWidthBottom = bwb;

                            callingListTbl.AddCell(cell);
                            callingListTbl.AddCell(cell);
                            callingListTbl.AddCell(cell);
                            callingListTbl.AddCell(cell);
                            callingListTbl.AddCell(cell);
                        }

                    }
                    doc.Add(callingListTbl);

                    ptable = new PdfPTable(3);
                    cell = new PdfPCell(new Phrase(new Chunk("", ClassTitleFont)));
                    cell.Colspan = 3;
                    cell.BorderWidth = 0;
                    cell.FixedHeight = 60f;
                    ptable.AddCell(cell);
                    doc.Add(ptable);

                    lineLeft = writer.GetVerticalPosition(false) - doc.BottomMargin;
                    if (lineLeft < 200)
                    {
                        doc.NewPage();
                    }
                    //doc.NewPage();
                    gradeidx++;
                }
            }

            return ret;
        }
        public RingPlannerForDay(int ShowDetailsId)
        {
            ShowDetails = new ShowDetails(ShowDetailsId);
            RingList = new List<RingDetails>();
            UnallocatedClasses = new List<ClassDetails>();
            UnallocatedHelpers = new List<Helper>();
            UnallocatedJudges = new List<JudgeDetails>();
            var rings = Rings.GetRingsForShowDayList(ShowDetails.ID);

            foreach (var ring in rings)
            {
                RingList.Add(CreateRing(ShowDetails, ring));
            }

            ShowDetails showDetails = new ShowDetails();
            DataRowCollection unallocatedClasses = showDetails.getUnallocatedClassFoDay(ShowDetailsId);
            foreach (DataRow row in unallocatedClasses)
            {
                ShowClasses sc = new ShowClasses(row);
                var Part = Convert.ToInt32(row["Part"]);
                var PartNo = "";
                var ClassName = row["ShortName"].ToString();
                if (sc.EntryType == 10)
                {
                    ClassName = row["Name"].ToString();
                    if (ClassName.Contains("Jumping"))
                        ClassName = "Jumping";
                    else if (ClassName.Contains("Agility"))
                        ClassName = "Agility";
                    else if (ClassName.Contains("Final"))
                        ClassName = "Final";
                    ClassName = string.Format("{0} {1} {2}",
                        ShowClasses.expandHeightShort(row),
                        sc.ShortClassName,
                        ClassName);
                }
                else
                {
                    PartNo = (Part == 0 ? "" : string.Format(" Pt {0}", Part));
                    ClassName = string.Format("{0} {1} {2} {3} {4}", ShowClasses.expandHeightShort(row),
                    ShowClasses.expandCatagoryShort(row),
                    ShowClasses.shortenName(row) + PartNo,
                    ClassName,
                    ShowClasses.shortenGrades(row));
                }

                UnallocatedClasses.Add(new ClassDetails
                {
                    ClassId = sc.ID,
                    DogsInClass = Convert.ToInt32(row["DogsInClass"]),
                    ClassNo = sc.ClassNo,
                    ClassName = ClassName,
                    JudgeId = Convert.ToInt32(row["JudgeId"])
                });
            }

            var data = Business.Helpers.GetAllHelpersForShow(ShowDetails.ShowID, "Name", 0);
            var Unallocated = data.Where(x => x.RingNo < 1 && x.ShowDetailsID == ShowDetailsId).OrderBy(z => (int)z.TimePeriod).ToList();
            foreach (var h in Unallocated)
            {
                UnallocatedHelpers.Add(new Helper {
                    HelperId = h.ID,
                    HelperName = h.Name,
                    JobDescription = Fpp.Core.Utils.expandJob(h.Job, h.JobDetails)
                });
            }

            DataSet ds = Judge.GetAllFreeJudgesForShow(ShowDetailsId);
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                UnallocatedJudges.Add(new JudgeDetails()
                {
                    JudgeName = Convert.ToString(row["Name"]),
                    JudgeId = Convert.ToInt32(row["JudgeId"]),
                });
            }
        }
        public void RingBoards(Document doc, int ShowId, int RingId)
        {
            Font smallFont = new Font(Font.COURIER, 8, Font.NORMAL, Color.BLACK);
            Font normalFont = new Font(Font.COURIER, 10, Font.NORMAL, Color.BLACK);
            Font mediumFont = new Font(Font.HELVETICA, 20, Font.NORMAL, Color.BLACK);
            ShowClasses sc = new ShowClasses();

            List<Rings> AllRings = new List<Rings>();
            if (RingId == -1)
            {
                AllRings = Rings.GetAllRingsForShow(ShowId);
            }
            else
            {
                AllRings.Add(new Rings(RingId));
            }
            var showDetailsList = ShowDetails.GetShowDetails(ShowId);
            Shows show = new Shows(ShowId);
            foreach (var showDetails in showDetailsList)
            {
                Rings rings = new Rings();
                var ringsForDays = Rings.GetRingsForShowDayList(showDetails.ID);
                //            var groupByRing = ringsForDays.GroupBy(x => x.RingNo);
                int lastRingNo = 0;
                foreach (Rings ring in ringsForDays)
                {
                    if (ring.ID > -1 && lastRingNo != ring.RingNo)
                    {
                        lastRingNo = ring.RingNo;
                        doc.NewPage();

                        DataSet judgesDS = Rings.GetJudgesForRing(ring.ID);
                        if (judgesDS.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow judgeRow in judgesDS.Tables[0].Rows)
                            {
                                Judge judge = new Judge(judgeRow);
                                CreateRing(doc, show, showDetails, ring, judge, "", lastRingNo);
                            }
                        }
                    }
                }
            }
            doc.NewPage();
        }
        public bool Delete()
        {
            Fpp.Data.ShowDetails showDetails = new Fpp.Data.ShowDetails(ModuleSettings);

            ShowClasses sc = new ShowClasses();
            sc.RemoveRing(ID);

            Judge j = new Judge();
            j.removeRing(ID);

            Fpp.Business.Helpers h = new Fpp.Business.Helpers();
            h.removeRing(ID);
            _ring.Delete(ID);

            int ringNo = 1;
            var rings = GetRingsForShowDayList(_showDetailsID).OrderBy(x => x.RingNo);
            foreach (var r in rings)
            {
                r.RingNo = ringNo;
                r.Save();
                ringNo++;
            }
            return true;
        }
        public int ScoreBoards(Document doc, int showId, int ringId, int position = -1)
        {
            var ret = 0;
            var bigBoyFont = new Font(Font.HELVETICA, 20, Font.BOLD, Color.BLACK);
            var sc = new ShowClasses();
            var currentRing = new Rings(ringId);
            var showClasses = ShowClasses.GetAllClassesForShowRing(showId, ringId, position);
            ret = showClasses.Count;
            float[] colWidthsTeam = { 30, 150, 150, 50, 50, 50 };
            float[] colWidths = { 30, 50, 150, 150, 50, 50, 50 };
            PdfPTable callingListTbl = null;
            var currentClassNo = 0;
            var multiClasses = TeamPairsManager.GetTeamPairClasses(showId);
            var multiTeams = TeamPairsManager.GetTeamPairsForShow(showId, multiClasses);

            foreach (var showClass in showClasses)
            {
                var grades = showClass.Grades;
                var gradeIdx = 0;

                do
                {
                    if (currentClassNo != showClass.ClassNo)
                    {
                        callingListTbl = TeamPairsManager.isMultiDog(showClass.EntryType) ? new PdfPTable(colWidthsTeam) : new PdfPTable(colWidths);
                        callingListTbl.HeaderRows = 2;
                    }

                    var currentGrade = Convert.ToInt32(showClass.Grades[gradeIdx]) - 48;
                    string tmp;
                    if (showClass.EntryType == 10)
                    {
                        grades = "";
                        tmp = string.Format("Ring {4} - Class {0}: {1} {2} {3}",
                            showClass.ClassNo, showClass.longHeight, showClass.LongClassName,
                            showClass.ClassName, currentRing.RingNo);
                    }
                    else
                    {
                        if (grades.Length == 1)
                        {
                            grades = "Grade " + grades;
                        }
                        else
                        {
                            grades = "Grades " + grades[0] + "-" + grades[grades.Length - 1];
                        }
                        tmp = showClass.Catagory == 0 ?
                            $"Ring {currentRing.RingNo} - Class {showClass.ClassNo}: {showClass.longHeight} Graded {showClass.LongClassName} Grade {currentGrade} {showClass.ClassName}{(showClass.Part > 0 ? " Part " + showClass.Part : "")}"
                            : $"Ring {currentRing.RingNo} - Class {showClass.ClassNo}: {showClass.NormalName(false)} {(showClass.Part > 0 ? " Part " + showClass.Part : "")}";
                    }
                    var cell = new PdfPCell(new Phrase(new Chunk(tmp, bigBoyFont)))
                    {
                        Colspan = 7,
                        BorderWidth = 0
                    };
                    callingListTbl.AddCell(cell);
                    doc.Add(callingListTbl);
                    DrawCourseBoxes(doc);

                    var callingList = showClass.Catagory == 0 ? sc.GetCallingList(showId, showClass.ID, currentGrade) : sc.GetCallingList(showId, showClass.ID);

                    ScoreBoardColumnHeaders(showClass, callingListTbl, callingList, colWidths);

                    if (TeamPairsManager.isMultiDog(showClass.EntryType))
                    {
                        TeamScoreBoard(multiTeams, showClass, callingListTbl);
                    }
                    else
                    {
                        var lhoCurrent = callingList.Any() ? callingList.First().Lho : 0;
                        var lineCnt = 0;
                        foreach (var item in callingList)
                        {

                            if (item.Lho != lhoCurrent)
                            {
                                doc.Add(callingListTbl);
                                doc.NewPage();
                                callingListTbl = new PdfPTable(colWidths);
                                lhoCurrent = item.Lho;

                                ScoreBoardColumnHeaders(showClass, callingListTbl, callingList, colWidths);
                                //var cnt = callingList.Count(x => x.Lho == item.Lho);
                                //var title = $"{(item.Lho == 0 ? "Full Height " : "Lower Height")} ({cnt})";
                                //callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk(title, headerHFont)))
                                //{
                                //    BorderWidth = 0,
                                //    Colspan = colWidths.Length,
                                //    BackgroundColor = Color.LIGHT_GRAY,
                                //    HorizontalAlignment = Element.ALIGN_CENTER,
                                //    FixedHeight = 20,
                                //    BorderColorBottom = Color.BLACK,
                                //    BorderWidthBottom = 2
                                //});
                            }

                            var altColor = (lineCnt % 2 == 0 ? Color.WHITE : Color.LIGHT_GRAY);
                            cell = new PdfPCell(new Phrase(new Chunk($"{item.Ro}", _normal10Black)))
                            {
                                BorderWidth = 0,
                                FixedHeight = 20f,
                                BackgroundColor = altColor,
                                HorizontalAlignment = Element.ALIGN_RIGHT
                            };
                            callingListTbl.AddCell(cell);

                            int borderWidth = 0;
                            if (showClass.EntryType == 5 || showClass.EntryType == 9) borderWidth = 1;
                            callingListTbl.AddCell(new PdfPCell(new Phrase(new Chunk($"{item.RingNumber}", _normal10Black)))
                            {
                                HorizontalAlignment = Element.ALIGN_RIGHT,
                                BackgroundColor = altColor,
                                BorderWidth = borderWidth
                            });

                            var handlerName = item.Name;
                            User user;
                            if (item.DefaultHandlerId > 0)
                            {
                                user = new User(item.DefaultHandlerId);
                                handlerName = user.Name;
                            }
                            if (item.AltHandlerId > 0)
                            {
                                user = new User(item.AltHandlerId);
                                handlerName = user.Name;
                            }

                            cell = new PdfPCell(new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(handlerName), _normal10Black)))
                            {
                                BackgroundColor = altColor,
                                BorderWidth = borderWidth
                            };
                            callingListTbl.AddCell(cell);

                            cell =
                                new PdfPCell(
                                    new Phrase(new Chunk(Fpp.Core.Utils.TitleCaseString(item.KcName), _normal10Black)))
                                {
                                    BackgroundColor = altColor,
                                    BorderWidth = borderWidth
                                };
                            callingListTbl.AddCell(cell);

                            cell = new PdfPCell(new Phrase(""));
                            cell.BorderWidth = 1;
                            if (showClass.EntryType == 4)
                            {
                                cell.BorderWidthBottom = 0;
                            }
                            callingListTbl.AddCell(cell);
                            cell = new PdfPCell(new Phrase(""));
                            cell.BackgroundColor = Color.WHITE;
                            cell.BorderWidth = 1;
                            if (showClass.EntryType == 4)
                            {
                                cell.BorderWidthBottom = 0;
                            }
                            callingListTbl.AddCell(cell);
                            callingListTbl.AddCell(cell);
                            lineCnt++;
                        }
                        cell = new PdfPCell(new Phrase(""));
                        cell.BorderWidth = 0;
                        cell.Colspan = 7;
                        cell.FixedHeight = 50f;
                        callingListTbl.AddCell(cell);
                    }

                    doc.Add(callingListTbl);
                    gradeIdx++;

                } while (showClass.Catagory == 0 && gradeIdx < showClass.Grades.Length);
                doc.NewPage();
            }

            return ret;
        }
        private string CreateTotalsSummaryEmail(int ShowID, int UserID, ref Decimal totals)
        {
            var classes = new ShowClasses();
            var totalsList = classes.getShowTotalsForUser(ShowID, UserID);
            var transSummary = new TransactionSummary(ShowID, UserID);
            var totalsBox = "<table>";
            totalsBox += "<tr >";

            foreach (var total in totalsList)
            {
                const string tmp = "<span class='infoSpacer'></span>";

                totalsBox += "<tr class='clsTypeRow group' entryType='" + total.EntryType + "' >";
                totalsBox += "<td  class='clsTypeName themeBorder-r themeContentHilite' chargename='" + total.ChargeName + "'>" + tmp + total.ChargeName + "</td>";
                totalsBox += "<td class='clsTypeRate themeBorder-r'>" + total.ChargeRate.ToString("0.00") + "</td>";
                totalsBox += "<td  class='clsTypeEntry themeBorder-r'>" + total.Count + "</td>";
                totalsBox += "<td class='clsTypeSubTotal'>" + total.Total.ToString("0.00") + "</td>";
                totalsBox += "</tr>";
                totals += total.Total;
            }

            if (transSummary.ID != -1)
            {
                totalsBox += "<tr class='clsTypeRow group prepaid'>";
                totalsBox += "<td class='clsTypePaymentInfo themeBorder-t themeContentHilite'>Payment Received</td>";
                totalsBox += "<td class='clsTypeTotal themeBorder-t themeBorder-l'>" + transSummary.Total.ToString("0.00") + "</td>";
                totalsBox += "</tr >";
                totals -= transSummary.Total;
            }

            totalsBox += "<tr class='clsTypeRow group fulltotal'>";
            if (totals > 0)
            {
                totalsBox += "<td class='clsTypePaymentInfo themeBorder-t themeContentHilite'>Payment Due</td>";
            }
            else if (totals < 0)
            {
                totalsBox += "<td class='clsTypePaymentInfo themeBorder-t themeContentHilite'>Payment Due</td>";
            }
            else
            {
                totalsBox += "<td class='clsTypePaymentInfo themeBorder-t themeContentHilite'>No Payment Due</td>";
            }
            totalsBox += "<td class='clsTypeTotal themeBorder-t themeBorder-l'>" + totals.ToString("0.00") + "</td>";
            totalsBox += "</tr >";
            totalsBox += "</table>";

            return totalsBox;
        }
        public ActionResult DogsInClass(int id)
        {
            var show = ShowClasses.GetShowFromClassId(id);
            var showClass = new ShowClasses(id);
            String grades = showClass.ShortenGrades();
            var clsName = String.Format("{0} {1} {2} {3} {4}",
                            showClass.ClassNo,
                            showClass.longCatagory,
                            showClass.longHeight,
                            showClass.LongClassName,
                            grades);

            var DogsInClass = new DogsInClassDto
            {
                DogsInClassDetails = DogClasses.GetDogsInClass(id),
                ShowName = show.ShowName,
                ShowId = show.ID,
                ShowDate = show.ShowDate,
                ClassName = clsName

            };
            return View(DogsInClass);
        }