Beispiel #1
0
        public IActionResult GenerateSchedule([FromBody] CourseInfoToSchedule courseInfo)
        {
            // Get the current user.
            var user = _userManager.GetUserAsync(User).Result;

            // Check if there are no course ids, if there arn't remove all courses from schedule.
            if (courseInfo.CourseIds?.Length == 0)
            {
                // Remove all user sections for this user.
                var sectionsForUser = _context.UserSections.Where(us => us.UserId == user.Id).ToList();
                _context.UserSections.RemoveRange(sectionsForUser ?? new List <UserSection>());
                _context.SaveChanges();
                return(Json(new ScheduleViewModel()
                {
                    Error = "Please add a class to generate a schedule."
                }));
            }

            Course[] courses = _context.Courses
                               .Include(c => c.Sections)
                               .ThenInclude(s => s.Professor)
                               .Include(c => c.Sections)
                               .ThenInclude(s => s.Meetings)
                               .ThenInclude(m => m.Location)
                               .Include(c => c.Cape)
                               .ThenInclude(ca => ca.Professor)
                               .ThenInclude(p => p.RateMyProfessor)
                               .Where(c => courseInfo.CourseIds.Contains(c.Id)).ToArray();
            Optimization optimization = courseInfo.Optimization;

            var scheduleRepo = new ScheduleRepo();

            // Call the schedule finding algorithm.
            PossibleSchedules schedules = scheduleRepo.FindScheduleForClasses(courses);

            if (!schedules.Any())
            {
                // TODO: return error
                return(Json(new ScheduleViewModel()
                {
                    Error = "No possible schedule for given courses."
                }));
            }


            List <Section> schedule = ScheduleOptimizationFactory.GetOptimization(optimization).Optimize(schedules);

            // Create user sections to add.
            var sectionsToAdd = schedule.Select(s => new UserSection {
                Section = s, User = user
            });
            // Get the schedule sections for this user.
            var sectionsToRemove = _context.UserSections.Where(us => us.User == user);

            // Remove old sections.
            _context.RemoveRange(sectionsToRemove);
            // Add new ones.
            _context.AddRange(sectionsToAdd);
            _context.SaveChanges();

            ScheduleViewModel model = FormatRepo.FormatSectionsToCalendarEvent(schedule);

            model.Error = "";

            return(Json(model));
        }