public virtual EdFiGridModel GetEdFiGridModel(bool displayInteractionMenu, bool displayAddRemoveColumns, int fixedHeight, string name, int? metricVariantId, GridTable gridTable, IList<MetricFootnote> metricFootnotes, string nonPersistedSettings, bool sizeToWindow, string listType, IList<string> legendViewNames, string hrefToUse, bool usePagination, string paginationCallbackUrl, bool allowMaximizeGrid,
     EdFiGridWatchListModel studentWatchList = null, string selectedDemographicOption = null, string selectedSchoolCategoryOption = null, string selectedGradeOption = null, string previousNextSessionPage = null, string exportGridDataUrl = null, ListType gridListType = default(ListType))
 {
     var model = new EdFiGridModel
     {
         DisplayInteractionMenu = displayInteractionMenu,
         DisplayAddRemoveColumns = displayAddRemoveColumns,
         FixedHeight = fixedHeight,
         GridName = name,
         GridTable = gridTable,
         SizeToWindow = sizeToWindow,
         UniqueTableName = name,
         MetricFootnotes = metricFootnotes,
         NonPersistedSettings = nonPersistedSettings,
         EntityList = string.IsNullOrEmpty(listType) ? null :
             new EntityListModel
             {
                 ListType = listType,
                 MetricVariantId =
                     metricVariantId.HasValue
                         ? metricVariantId.Value.ToString(CultureInfo.InvariantCulture)
                         : string.Empty,
                 RowIndexForId = 1
             },
         LegendViewNames = legendViewNames,
         DefaultSortColumn = 1,
         HrefToUse = hrefToUse,
         UsePagination = usePagination,
         PaginationCallbackUrl = paginationCallbackUrl,
         AllowMaximizeGrid = allowMaximizeGrid,
         StudentWatchList = studentWatchList,
         SelectedDemographicOption = selectedDemographicOption,
         SelectedSchoolCategoryOption = selectedSchoolCategoryOption,
         SelectedGradeOption = selectedGradeOption,
         PreviousNextSessionPage = previousNextSessionPage,
         ExportGridDataUrl = exportGridDataUrl,
         ListType = gridListType
     };
     return model;
 }
        /// <summary>
        /// Loads the watch list with the saved selections.
        /// </summary>
        /// <param name="model">The watch list model.</param>
        /// <param name="selectedOptions">The selected options.</param>
        /// <returns>An <see cref="EdFiGridWatchListModel"/> with the selections loaded.</returns>
        protected virtual EdFiGridWatchListModel LoadWatchListSelections(EdFiGridWatchListModel model, List<NameValuesType> selectedOptions)
        {
            // this code will get the view models for all of the templates in
            // all of the columns in all of the tabs
            var viewModels = new List<object>();
            foreach (var column in model.Tabs.SelectMany(tab => tab.Columns))
            {
                viewModels.AddRange(column.Templates.GetViewModelsFromTemplates());
            }

            // loop through all of the view models and set the IsSelected
            // property to true where selections were made
            foreach (var viewModel in viewModels)
            {
                switch (viewModel.GetType().Name)
                {
                    case "EdFiGridWatchListSingleSelectionModel":
                        var singleSelectionModel = viewModel as EdFiGridWatchListSingleSelectionModel;

                        if (singleSelectionModel != null)
                        {
                            if (selectedOptions.Any(data => data.Name == singleSelectionModel.Name))
                            {
                                var selectedOption = selectedOptions.SingleOrDefault(data => data.Name == singleSelectionModel.Name);

                                if (selectedOption != null)
                                {
                                    foreach (var singleSelectionModelValue in selectedOption.Values.Select(value => singleSelectionModel.Values.SingleOrDefault(data => data.Name == value)).Where(singleSelectionModelValue => singleSelectionModelValue != null))
                                    {
                                        singleSelectionModelValue.IsSelected = true;
                                    }
                                }
                            }
                        }
                        break;
                    case "EdFiGridWatchListDoubleSelectionModel":
                        var doubleDropDownModel = viewModel as EdFiGridWatchListDoubleSelectionModel;

                        if (doubleDropDownModel != null)
                        {
                            if (selectedOptions.Any(data => data.Name == doubleDropDownModel.Name))
                            {
                                var selectedOption = selectedOptions.SingleOrDefault(data => data.Name == doubleDropDownModel.Name);

                                if (selectedOption != null)
                                {
                                    foreach (var value in selectedOption.Values)
                                    {
                                        var comparison = doubleDropDownModel.Comparisons.SingleOrDefault(data => data.Name == value);
                                        if (comparison != null)
                                        {
                                            comparison.IsSelected = true;
                                            continue;
                                        }

                                        var selectedValue = doubleDropDownModel.Values.SingleOrDefault(data => data.Name == value);
                                        if (selectedValue != null)
                                        {
                                            selectedValue.IsSelected = true;
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    case "EdFiGridWatchListDoubleSelectionTextboxModel":
                        var dropDownTextBoxModel = viewModel as EdFiGridWatchListDoubleSelectionTextboxModel;

                        if (dropDownTextBoxModel != null)
                        {
                            if (selectedOptions.Any(data => data.Name == dropDownTextBoxModel.Name))
                            {
                                var selectionOption = selectedOptions.SingleOrDefault(data => data.Name == dropDownTextBoxModel.Name);

                                if (selectionOption != null)
                                {
                                    foreach (var value in selectionOption.Values)
                                    {
                                        var comparison = dropDownTextBoxModel.Comparisons.SingleOrDefault(data => data.Name == value);
                                        if (comparison != null)
                                        {
                                            comparison.IsSelected = true;
                                            continue;
                                        }

                                        dropDownTextBoxModel.SelectionValue = value;
                                    }
                                }
                            }
                        }
                        break;
                }
            }

            return model;
        }
        /// <summary>
        /// Gets the EdFiGridWatchListModel; the structure will be determined
        /// by the logged in user.
        /// </summary>
        /// <param name="staffUSI">The staff USI.</param>
        /// <param name="schoolId">The school identifier.</param>
        /// <param name="localEducationAgencyId">The local education agency identifier.</param>
        /// <param name="sectionId">The section identifier.</param>
        /// <param name="watchListSelections">The watch list selections.</param>
        /// <returns>
        /// An <see cref="EdFiGridWatchListModel" /> loaded with data for the currently logged in user.
        /// </returns>
        public virtual EdFiGridWatchListModel GetEdFiGridWatchListModel(long staffUSI, int? schoolId, int? localEducationAgencyId = null, long? sectionId = null, List<NameValuesType> watchListSelections = null)
        {
            var watchListDataState = new WatchListDataState();

            var defaultStudentMetricsProviderOptions = new StudentMetricsProviderQueryOptions
            {
                StaffUSI = staffUSI,
                SchoolId = schoolId,
                LocalEducationAgencyId = localEducationAgencyId,
                GetAllMetrics = true
            };

            watchListDataState.Students = GetStudentList(defaultStudentMetricsProviderOptions);
            watchListDataState.Metrics = GetStudentMetrics(defaultStudentMetricsProviderOptions);

            var grades = watchListDataState.Students.Select(data => new { data.GradeLevel, data.GradeLevelSortOrder }).Distinct().OrderBy(order => order.GradeLevelSortOrder).ToList();
            watchListDataState.Grades = grades.Select(data => new EdFiGridWatchListSelectionItemModel { DisplayValue = data.GradeLevel, Name = data.GradeLevel }).ToList();

            watchListDataState.MetricIds = watchListDataState.Metrics.Select(data => data.MetricId).Distinct().ToList();

            var results = new List<TeacherSection>();

            if (schoolId.HasUsableValue())
            {
                results = (TeacherSectionRepository.GetAll()
                    .Where(data => data.StaffUSI == staffUSI && data.SchoolId == schoolId)
                    .OrderBy(data => data.SubjectArea).ThenBy(data => data.CourseTitle)
                    .ThenBy(data => data.ClassPeriod).ThenBy(data => data.LocalCourseCode)
                    .ThenBy(data => data.TeacherSectionId)).ToList();
            }

            if (sectionId.HasUsableValue())
            {
                watchListDataState.CurrentSectionId = sectionId.Value;
            }

            watchListDataState.Sections = results.ToDictionary(
                key => key.TeacherSectionId,
                value => String.Format(SectionDescriptionFormat, value.SubjectArea, value.LocalCourseCode, value.CourseTitle, value.ClassPeriod, value.TermType)
            );

            // determine if the section id has a value and if that value is
            // contained in the sections dictionary above; if not the section
            // id is really a watch list id
            var isWatchListSection = sectionId.HasUsableValue() && (!(sectionId.Value <= int.MaxValue ? (int?) sectionId.Value : null).HasValue || !watchListDataState.Sections.ContainsKey((int) sectionId.Value));

            MetricBasedWatchList watchList = null;
            List<NameValuesType> watchListSelectedOptions = null;

            if (isWatchListSection)
            {
                watchList = GetWatchListData(sectionId.Value);
                watchListSelectedOptions = GetWatchListSelectionData(sectionId.Value);
            }

            var isWatchListChanged = false;
            // if this parameter is set then we are coming back from a watch
            // list and need to reset to the last values selected
            if (watchListSelections != null)
            {
                isWatchListChanged = IsWatchListChanged(watchListSelections, watchListSelectedOptions);
                watchListSelectedOptions = watchListSelections;
            }

            var searchLinkRequest = new WatchListLinkRequest
            {
                LocalEducationAgencyId = localEducationAgencyId,
                SchoolId = schoolId,
                StaffUSI = staffUSI,
                MetricBasedWatchListId = (int?)sectionId,
                ResourceName = "MetricsBasedWatchListSearch"
            };

            // create the watch list model
            var watchListModel = new EdFiGridWatchListModel
            {
                WatchListName = (watchList != null && watchList.WatchListName != string.Empty ? watchList.WatchListName : "New Dynamic List"),
                WatchListDescription = (watchList != null ? watchList.WatchListDescription : string.Empty),
                WatchListUrl = GeneralLinks.MetricsBasedWatchList("MetricsBasedWatchList"),
                WatchListSearchUrl = WatchListLinkProvider.GenerateLink(searchLinkRequest),
                IsWatchListChanged = isWatchListChanged,
                IsWatchListShared = watchList != null && watchList.IsWatchListShared,
                Tabs = TabFactory.CreateAllTabs(watchListDataState)
            };

            // load any available selections into the model
            if (watchListSelectedOptions != null)
            {
                LoadWatchListSelections(watchListModel, watchListSelectedOptions);
            }

            return watchListModel;
        }
        /// <summary>
        /// Creates the model selections from the watch list model data.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        protected virtual string CreateModelSelections(EdFiGridWatchListModel model)
        {
            // first get all of the typed view models
            var viewModels = new List<object>();
            foreach (var column in model.Tabs.SelectMany(tab => tab.Columns))
            {
                viewModels.AddRange(column.Templates.GetViewModelsFromTemplates());
            }

            var itemList = new List<NameValuesType>();
            foreach (var viewModel in viewModels)
            {
                switch (viewModel.GetType().Name)
                {
                    case "EdFiGridWatchListSingleSelectionModel":
                        var singleSelectionModel = viewModel as EdFiGridWatchListSingleSelectionModel;
                        if (singleSelectionModel == null)
                            continue;

                        var selectedSingleValues = singleSelectionModel.Values.Where(item => item.IsSelected).ToList();
                        if (selectedSingleValues.Any())
                        {
                            var selectedItemValues = selectedSingleValues.Select(selectedValue => selectedValue.DisplayValue).ToList();
                            itemList.Add(new NameValuesType
                            {
                                Name = singleSelectionModel.DisplayValue,
                                Values = selectedItemValues
                            });
                        }
                        break;
                    case "EdFiGridWatchListDoubleSelectionModel":
                        var doubleSelectionModel = viewModel as EdFiGridWatchListDoubleSelectionModel;
                        if (doubleSelectionModel == null)
                            continue;

                        var selectedComparisons = doubleSelectionModel.Comparisons.Where(item => item.IsSelected).ToList();
                        if (selectedComparisons.Any())
                        {
                            var dropDownComparisonValues = selectedComparisons.Select(item => item.DisplayValue).ToList();
                            // if there are defined values then check to see
                            // which one is selected
                            if (doubleSelectionModel.Values != null)
                            {
                                var selectedValues = doubleSelectionModel.Values.Where(item => item.IsSelected).ToList();

                                if (selectedValues.Any())
                                {
                                    dropDownComparisonValues.Add(
                                        selectedValues.Select(item => item.DisplayValue).SingleOrDefault());
                                }
                            }

                            itemList.Add(new NameValuesType
                            {
                                Name = doubleSelectionModel.DisplayValue,
                                Values = dropDownComparisonValues
                            });
                        }
                        break;
                    case "EdFiGridWatchListDoubleSelectionTextboxModel":
                        var doubleSelectionTextboxModel = viewModel as EdFiGridWatchListDoubleSelectionTextboxModel;
                        if (doubleSelectionTextboxModel == null)
                            continue;

                        var selectedTextboxComparisons = doubleSelectionTextboxModel.Comparisons.Where(item => item.IsSelected).ToList();
                        if (selectedTextboxComparisons.Any())
                        {
                            // for the drop down/text box items there will be
                            // one selected item and a text box value
                            var comparisonValues = selectedTextboxComparisons.Select(item => item.DisplayValue).ToList();
                            comparisonValues.Add(doubleSelectionTextboxModel.SelectionValue);

                            itemList.Add(new NameValuesType
                            {
                                Name = doubleSelectionTextboxModel.DisplayValue,
                                Values = comparisonValues
                            });
                        }
                        break;
                }
            }

            var returnString = string.Empty;
            foreach (var item in itemList)
            {
                returnString += item.Name + ": ";
                returnString = item.Values.Aggregate(returnString, (current, value) => current + (value + ", "));
            }

            return returnString.TrimEnd(' ', ',');
        }
 /// <summary>
 /// Creates the selection text from a loaded watch list model.
 /// </summary>
 /// <param name="request">The request used to create the selection text.</param>
 /// <returns>
 /// A string representation of the loaded watch list data.
 /// </returns>
 public string CreateSelectionText(EdFiGridWatchListModel request)
 {
     var selectionText = CreateModelSelections(request);
     return selectionText;
 }
 protected override void ExecuteTest()
 {
     metricsBasedWatchListDataProvider = new MetricsBasedWatchListDataProvider(
         null, null, null, studentMetricsProvider, watchListLinkProvider, generalLinks, tabFactory);
     result = metricsBasedWatchListDataProvider.GetEdFiGridWatchListModel(TestStaffUsi, null);
 }