public async Task <IActionResult> Index(
            string level,
            Guid?courseId,
            Guid?courseRunId,
            string notificationTitle,
            string notificationMessage)
        {
            int?UKPRN = Session.GetInt32("UKPRN");

            if (!UKPRN.HasValue)
            {
                return(RedirectToAction("Index", "Home", new { errmsg = "Please select a Provider." }));
            }

            var courseResult = (await _courseService.GetCoursesByLevelForUKPRNAsync(new CourseSearchCriteria(UKPRN))).Value;
            var venueResult  = (await _venueService.SearchAsync(new VenueSearchCriteria(UKPRN.ToString(), string.Empty))).Value;
            var allRegions   = _courseService.GetRegions().RegionItems;

            var levelFilters = courseResult
                               .Value
                               .Select(x => new QualificationLevelFilterViewModel
            {
                Name       = $"Level {x.Level}",
                Value      = x.Level,
                Facet      = x.Value.Count().ToString(),
                IsSelected = level == x.Level
            })
                               .OrderBy(x => x.Value)
                               .ToList();

            if (string.IsNullOrWhiteSpace(level))
            {
                level = levelFilters.FirstOrDefault()?.Value;
                levelFilters.ForEach(x => { if (x.Value == level)
                                            {
                                                x.IsSelected = true;
                                            }
                                     });
            }

            var courseViewModels = courseResult
                                   .Value
                                   .SingleOrDefault(x => x.Level == level)
                                   ?.Value
                                   .SelectMany(x => x.Value)
                                   .Select(x => new CourseViewModel
            {
                Id                 = x.id.ToString(),
                AwardOrg           = x.AwardOrgCode,
                LearnAimRef        = x.LearnAimRef,
                NotionalNVQLevelv2 = x.NotionalNVQLevelv2,
                QualificationTitle = x.QualificationCourseTitle,
                QualificationType  = x.QualificationType,
                CourseRuns         = x.CourseRuns.Select(y => new CourseRunViewModel
                {
                    Id                = y.id.ToString(),
                    CourseId          = y.ProviderCourseID,
                    AttendancePattern = y.AttendancePattern.ToDescription(),
                    Cost              = y.Cost.HasValue ? $"£ {y.Cost.Value:0.00}" : string.Empty,
                    CourseName        = y.CourseName,
                    DeliveryMode      = y.DeliveryMode.ToDescription(),
                    Duration          = y.DurationValue.HasValue ? $"{y.DurationValue.Value} {y.DurationUnit.ToDescription()}" : $"0 {y.DurationUnit.ToDescription()}",
                    Venue             = y.VenueId.HasValue ? FormatAddress(GetVenueByIdFrom(venueResult.Value, y.VenueId.Value)) : string.Empty,
                    Region            = y.Regions != null ? FormattedRegionsByIds(allRegions, y.Regions) : string.Empty,
                    StartDate         = y.FlexibleStartDate ? "Flexible start date" : y.StartDate?.ToString("dd/mm/yyyy"),
                    StudyMode         = y.StudyMode.ToDescription(),
                    Url               = y.CourseURL
                })
                                     .OrderBy(y => y.CourseName)
                                     .ToList()
            })
                                   .OrderBy(x => x.QualificationTitle)
                                   .ToList();

            var notificationCourseName = string.Empty;
            var notificationAnchorTag  = string.Empty;

            if (courseId.HasValue && courseId.Value != Guid.Empty)
            {
                notificationCourseName = QualificationTitleByCourseId(courseViewModels, courseId.ToString());

                if (courseRunId.HasValue && courseRunId.Value != Guid.Empty)
                {
                    var courseRuns = courseViewModels.Find(x => x.Id == courseId.Value.ToString())?.CourseRuns;
                    notificationCourseName = Regex.Replace(CourseNameByCourseRunId(courseRuns, courseRunId.ToString()), "<.*?>", String.Empty);
                }
            }

            notificationAnchorTag = courseRunId.HasValue
                ? $"<a id=\"courseeditlink\" class=\"govuk-link\" href=\"#\" data-courseid=\"{courseId}\" data-courserunid=\"{courseRunId}\" >{notificationCourseName} {notificationMessage}</a>"
                : $"<a id=\"courseeditlink\" class=\"govuk-link\" href=\"#\" data-courseid=\"{courseId}\">{notificationCourseName} {notificationMessage}</a>";

            var viewModel = new YourCoursesViewModel
            {
                Heading             = $"Level {level}",
                HeadingCaption      = "Your courses",
                Courses             = courseViewModels ?? new List <CourseViewModel>(),
                LevelFilters        = levelFilters,
                NotificationTitle   = notificationTitle,
                NotificationMessage = notificationAnchorTag
            };

            return(View(viewModel));
        }
        public async Task <IActionResult> Index(string status, string learnAimRef, string numberOfNewCourses, string errmsg)
        {
            var deliveryModes = new List <SelectListItem>();
            var durationUnits = new List <SelectListItem>();
            var attendances   = new List <SelectListItem>();
            var modes         = new List <SelectListItem>();


            if (!string.IsNullOrEmpty(status))
            {
                ViewData["Status"] = status;
                if (status.Equals("good", StringComparison.InvariantCultureIgnoreCase))
                {
                    ViewData["StatusMessage"] = string.Format("{0} New Course(s) created in Course Directory for LARS: {1}", numberOfNewCourses, learnAimRef);
                }
                else if (status.Equals("bad", StringComparison.InvariantCultureIgnoreCase))
                {
                    ViewData["StatusMessage"] = errmsg;
                }
                else
                {
                    // unhandled status
                }
            }



            var courseRunVenues = new List <SelectListItem>();

            var UKPRN = _session.GetInt32("UKPRN");

            if (UKPRN.HasValue)
            {
                VenueSearchCriteria criteria = new VenueSearchCriteria(UKPRN.ToString(), null);

                var venues = await _venueService.SearchAsync(criteria);

                foreach (var venue in venues.Value.Value)
                {
                    var item = new SelectListItem
                    {
                        Text = venue.VenueName, Value = venue.ID
                    };

                    courseRunVenues.Add(item);
                }
                ;
            }

            foreach (DeliveryMode eVal in DeliveryMode.GetValues(typeof(DeliveryMode)))
            {
                if (eVal.ToString().ToUpper() != "UNDEFINED")
                {
                    var item = new SelectListItem
                    {
                        Text = System.Enum.GetName(typeof(DeliveryMode), eVal), Value = eVal.ToString()
                    };

                    deliveryModes.Add(item);
                }
            }
            ;

            foreach (DurationUnit eVal in DurationUnit.GetValues(typeof(DurationUnit)))
            {
                if (eVal.ToString().ToUpper() != "UNDEFINED")
                {
                    var item = new SelectListItem
                    {
                        Text = System.Enum.GetName(typeof(DurationUnit), eVal), Value = eVal.ToString()
                    };

                    durationUnits.Add(item);
                }
            }
            ;

            foreach (AttendancePattern eVal in AttendancePattern.GetValues(typeof(AttendancePattern)))
            {
                if (eVal.ToString().ToUpper() != "UNDEFINED")
                {
                    var item = new SelectListItem
                    {
                        Text = System.Enum.GetName(typeof(AttendancePattern), eVal), Value = eVal.ToString()
                    };

                    attendances.Add(item);
                }
            }
            ;

            foreach (Dfc.CourseDirectory.Models.Models.Courses.StudyMode eVal in Enum.GetValues(typeof(Dfc.CourseDirectory.Models.Models.Courses.StudyMode)))
            {
                if (eVal.ToString().ToUpper() != "UNDEFINED")
                {
                    var item = new SelectListItem
                    {
                        Text = System.Enum.GetName(typeof(Dfc.CourseDirectory.Models.Models.Courses.StudyMode), eVal), Value = eVal.ToString()
                    };

                    modes.Add(item);
                }
            }
            ;

            // Get courses (and runs) for PRN, grouped by qualification type, then within that by LARS ref
            int?ukprn = _session.GetInt32("UKPRN");
            ICourseSearchResult result = (!ukprn.HasValue ? null :
                                          _courseService.GetYourCoursesByUKPRNAsync(new CourseSearchCriteria(ukprn))
                                          .Result.Value);

            YourCoursesViewModel vm = new YourCoursesViewModel
            {
                UKPRN         = ukprn,
                Courses       = result,
                deliveryModes = deliveryModes,
                durationUnits = durationUnits,
                attendances   = attendances,
                modes         = modes,
                Venues        = courseRunVenues
            };

            return(View(vm));
        }
        public async Task <IActionResult> Courses(
            string level,
            Guid?courseId,
            Guid?courseRunId,
            string notificationTitle,
            string notificationMessage)
        {
            Session.SetString("Option", "Courses");
            int?UKPRN = Session.GetInt32("UKPRN");

            var courseResult = (await _courseService.GetCoursesByLevelForUKPRNAsync(new CourseSearchCriteria(UKPRN))).Value;
            var venueResult  = (await _venueService.SearchAsync(new VenueSearchCriteria(UKPRN.ToString(), string.Empty))).Value;
            var allRegions   = _courseService.GetRegions().RegionItems;


            var Courses = courseResult.Value.SelectMany(o => o.Value).SelectMany(i => i.Value).ToList();

            var filteredCourses = from Course c in Courses.Where(c => BitmaskHelper.IsSet(c.CourseStatus, RecordStatus.Live)).ToList().OrderBy(x => x.QualificationCourseTitle)
                                  select c;

            var pendingCourses = from Course c in Courses.Where(c => c.CourseStatus == RecordStatus.MigrationPending || c.CourseStatus == RecordStatus.BulkUploadPending)
                                 select c;

            foreach (var course in filteredCourses)
            {
                var filteredCourseRuns = new List <CourseRun>();

                filteredCourseRuns = course.CourseRuns.ToList();
                filteredCourseRuns.RemoveAll(x => x.RecordStatus != RecordStatus.Live);

                course.CourseRuns = filteredCourseRuns;
            }

            var levelFilters = filteredCourses.GroupBy(x => x.NotionalNVQLevelv2).OrderBy(x => x.Key).ToList();

            var levelFiltersForDisplay = new List <QualificationLevelFilterViewModel>();

            var courseViewModels = new List <CourseViewModel>();

            if (string.IsNullOrWhiteSpace(level))
            {
                level = levelFilters.FirstOrDefault()?.Key;
            }
            else
            {
                if (!filteredCourses.Any(x => x.NotionalNVQLevelv2 == level))
                {
                    level = levelFilters.FirstOrDefault()?.Key;
                }
            }

            foreach (var levels in levelFilters)
            {
                var lf = new QualificationLevelFilterViewModel()
                {
                    Facet      = levels.ToList().Count().ToString(),
                    IsSelected = level == levels.Key,
                    Value      = levels.Key,
                    Name       = $"Level {levels.Key}",
                };

                levelFiltersForDisplay.Add(lf);

                foreach (var course in levels)
                {
                    if (course.NotionalNVQLevelv2 == level)
                    {
                        var courseVM = new CourseViewModel()
                        {
                            Id                 = course.id.ToString(),
                            AwardOrg           = course.AwardOrgCode,
                            LearnAimRef        = course.LearnAimRef,
                            NotionalNVQLevelv2 = course.NotionalNVQLevelv2,
                            QualificationTitle = course.QualificationCourseTitle,
                            QualificationType  = course.QualificationType,
                            Facet              = course.CourseRuns.Count().ToString(),
                            CourseRuns         = course.CourseRuns.Select(y => new CourseRunViewModel
                            {
                                Id                = y.id.ToString(),
                                CourseId          = y.ProviderCourseID,
                                AttendancePattern = y.AttendancePattern.ToDescription(),
                                Cost              = y.Cost.HasValue ? $"£ {y.Cost.Value:0.00}" : string.Empty,
                                CourseName        = y.CourseName,
                                DeliveryMode      = y.DeliveryMode.ToDescription(),
                                Duration          = y.DurationValue.HasValue
                                        ? $"{y.DurationValue.Value} {y.DurationUnit.ToDescription()}"
                                        : $"0 {y.DurationUnit.ToDescription()}",
                                Venue = y.VenueId.HasValue
                                        ? FormatAddress(GetVenueByIdFrom(venueResult.Value, y.VenueId.Value))
                                        : string.Empty,
                                Region = y.Regions != null
                                        ? FormattedRegionsByIds(allRegions, y.Regions)
                                        : string.Empty,
                                StartDate = y.FlexibleStartDate
                                        ? "Flexible start date"
                                        : y.StartDate?.ToString("dd/MM/yyyy"),
                                StudyMode = y.StudyMode == Services.Models.Courses.StudyMode.Undefined
                                        ? string.Empty
                                        : y.StudyMode.ToDescription(),
                                Url = y.CourseURL
                            })
                                                 .OrderBy(y => y.CourseName)
                                                 .ToList()
                        };

                        courseViewModels.Add(courseVM);
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(level))
            {
                level = levelFiltersForDisplay.FirstOrDefault()?.Value;
                levelFiltersForDisplay.ForEach(x => { if (x.Value == level)
                                                      {
                                                          x.IsSelected = true;
                                                      }
                                               });
            }

            courseViewModels.OrderBy(x => x.QualificationTitle).ToList();

            var notificationCourseName = string.Empty;
            var notificationAnchorTag  = string.Empty;

            if (courseId.HasValue && courseId.Value != Guid.Empty)
            {
                notificationCourseName = QualificationTitleByCourseId(courseViewModels, courseId.ToString());

                if (courseRunId.HasValue && courseRunId.Value != Guid.Empty)
                {
                    var courseRuns = courseViewModels.Find(x => x.Id == courseId.Value.ToString())?.CourseRuns;
                    notificationCourseName = CourseNameByCourseRunId(courseRuns, courseRunId.ToString());
                }
            }

            if (!courseRunId.HasValue)
            {
                notificationMessage = string.Empty;
            }

            notificationCourseName = Regex.Replace(notificationCourseName, "<.*?>", String.Empty);
            notificationAnchorTag  = courseRunId.HasValue
                ? $"<a id=\"courseeditlink\" class=\"govuk-link\" href=\"#\" data-courseid=\"{courseId}\" data-courserunid=\"{courseRunId}\" >{notificationMessage} {notificationCourseName}</a>"
                : $"<a id=\"courseeditlink\" class=\"govuk-link\" href=\"#\" data-courseid=\"{courseId}\">{notificationMessage} {notificationCourseName}</a>";

            var viewModel = new YourCoursesViewModel
            {
                Heading             = $"Level {level}",
                HeadingCaption      = "Your courses",
                Courses             = courseViewModels ?? new List <CourseViewModel>(),
                LevelFilters        = levelFiltersForDisplay,
                NotificationTitle   = notificationTitle,
                NotificationMessage = notificationAnchorTag,
                PendingCoursesCount = pendingCourses?.Count()
            };

            return(View(viewModel));
        }
 public async Task <IViewComponentResult> InvokeAsync(YourCoursesViewModel model)
 {
     return(View("~/ViewComponents/YourCourses/Course/Default.cshtml", model));
 }