public async Task <ActionResult> AnnotateImages(int incidentId)
        {
            var sharePointToken = AuthenticationHelper.GetAccessTokenAsync(AppSettings.DemoSiteServiceResourceId);
            var oneNoteToken    = AuthenticationHelper.GetOneNoteAccessTokenAsync();

            var graphService     = AuthenticationHelper.GetGraphServiceAsync();
            var dashboardService = new Dashboard(await sharePointToken);

            var oneNoteServiceFactory = new OneNoteServiceFactory(AADAppSettings.OneNoteResourceUrl, await oneNoteToken);
            var pageUrl = await dashboardService.AnnotateImagesAsync(await graphService, oneNoteServiceFactory, Server.MapPath("/"), incidentId);

            return(Redirect(pageUrl));
        }
        public async Task<ActionResult> InspectionDetails(int id)
        {
            var outlookToken = await AuthenticationHelper.GetAccessTokenAsync(AADAppSettings.OutlookResourceId);
            var sharePointToken = AuthenticationHelper.GetAccessTokenAsync(AppSettings.DemoSiteServiceResourceId);
            var graphService = AuthenticationHelper.GetGraphServiceAsync();

            var oneNoteToken = AuthenticationHelper.GetOneNoteAccessTokenAsync();
            var oneNoteServiceFactory = new OneNoteServiceFactory(AADAppSettings.OneNoteResourceUrl, await oneNoteToken);

            Dashboard dashboardModel = new Dashboard(await sharePointToken);
            var model = await dashboardModel.GetDashboardInspectionDetailsViewModelAsync(await graphService, oneNoteServiceFactory, id, User.Identity.Name);
            if (model == null) return HttpNotFound();

            return View(model);
        }
        public async Task <ActionResult> InspectionDetails(int id)
        {
            var outlookToken = await AuthenticationHelper.GetAccessTokenAsync(AADAppSettings.OutlookResourceId);

            var sharePointToken = AuthenticationHelper.GetAccessTokenAsync(AppSettings.DemoSiteServiceResourceId);
            var graphService    = AuthenticationHelper.GetGraphServiceAsync();

            var oneNoteToken          = AuthenticationHelper.GetOneNoteAccessTokenAsync();
            var oneNoteServiceFactory = new OneNoteServiceFactory(AADAppSettings.OneNoteResourceUrl, await oneNoteToken);

            Dashboard dashboardModel = new Dashboard(await sharePointToken);
            var       model          = await dashboardModel.GetDashboardInspectionDetailsViewModelAsync(await graphService, oneNoteServiceFactory, id, User.Identity.Name);

            if (model == null)
            {
                return(HttpNotFound());
            }

            return(View(model));
        }
        public async Task <DashboardInspectionDetailsViewModel> GetDashboardInspectionDetailsViewModelAsync(Graph.GraphService graphService, OneNoteServiceFactory oneNoteServiceFactory, int incidentId, string CurrentUser)
        {
            Task <Graph.IUser[]> getRepairPeople = null;
            Task <RepairPhoto[]> getRepairPhotos = null;

            var videos = GetVideosAsync(AppSettings.VideoPortalIncidentsChannelName, incidentId);

            var incident = await GetIncidentByIdAsync(incidentId);

            if (incident.sl_inspectionIDId == null)
            {
                return(null);
            }

            var property       = incident.sl_propertyID;
            var propertyImgUrl = GetPropertyPhotoAsync(property.Id);

            var inspectionID        = incident.sl_inspectionIDId.Value;
            var inspection          = GetInspectionByIdAsync(inspectionID);
            var getInspectionPhotos = GetInspectionPhotosAsync(inspectionID);

            var incidentStatus = incident.sl_status;

            if (incidentStatus == "Pending Assignment")
            {
                getRepairPeople = graphService.GetGroupMembersAsync("Repair People");
            }
            if (incidentStatus == "Repair Pending Approval" || incidentStatus == "Repair Approved")
            {
                getRepairPhotos = GetRepairPhotosAsync(incidentId);
            }

            var unifiedGroupFetcher = graphService.groups.GetById(property.sl_group);
            var unifiedGroup        = unifiedGroupFetcher.ExecuteAsync();
            var groupFiles          = GetGroupFilesAsync(unifiedGroupFetcher, (await unifiedGroup).mailNickname);
            var groupConversations  = GetConversationsAsync(unifiedGroupFetcher, (await unifiedGroup).mail);

            var notebookName   = (await unifiedGroup).displayName + " Notebook";;
            var oneNoteService = oneNoteServiceFactory.CreateOneNoteServiceForUnifiedGroup(await unifiedGroup);
            var notebook       = GetOrCreateNoteBook(await oneNoteService, notebookName);
            var pages          = (await notebook) != null
                ? GetOneNotePagesAsync(await oneNoteService, (await notebook).Id, property.Title, incidentId)
                : Task.FromResult(new HyperLink[0]);

            // Repair people are included in property group.
            // Before we get members of a group, we must make sure that repair people have been retrieved.
            // Otherwise, we'll get an error:
            //         The context is already tracking a different entity with the same resource Uri.
            if (getRepairPeople != null)
            {
                await getRepairPeople;
            }
            var groupMembers = graphService.GetGroupMembersAsync(unifiedGroupFetcher);

            var recentEarliestDateTime = new DateTimeOffset(DateTime.UtcNow).AddDays(-7);
            var recentDocuments        = (await groupFiles)
                                         .Where(i => i.dateTimeLastModified > recentEarliestDateTime)
                                         .ToList();

            property.propertyImgUrl = await propertyImgUrl;

            var isCurrentUserDispatcher = CurrentUser == AppSettings.DispatcherEmail;


            var viewModel = new DashboardInspectionDetailsViewModel
            {
                viewName             = IncidentStatusViewMappings[incidentStatus],
                PropertyDetail       = property,
                incidentId           = incidentId,
                incident             = incident,
                UnifiedGroupNickName = (await unifiedGroup).mailNickname,
                UnifiedGroupId       = (await unifiedGroup).objectId,
                UnifiedGroupEmail    = (await unifiedGroup).mail,
                inspection           = await inspection,
                videos = await videos,
                files  = (await groupFiles)
                         .Select(i => HyperLink.Create(i.name, i.webUrl))
                         .ToArray(),
                recentDocuments = recentDocuments
                                  .Select(i => HyperLink.Create(i.name, i.webUrl))
                                  .ToArray(),
                members = await groupMembers,
                roomInspectionPhotos = await getInspectionPhotos,
                inspectionComment    = await GetInspectionCommentAsync(inspectionID, incident.sl_roomID.Id),
                //tasks = await GetTaskHyperLinksAsync(unifiedGroup)
                repairPeople    = getRepairPeople != null ? await getRepairPeople : new Graph.IUser[0],
                repairPhotos    = getRepairPhotos != null ? await getRepairPhotos : new RepairPhoto[0],
                DispatcherMails = isCurrentUserDispatcher ? await GetMailsForDispatcherAsync(graphService, CurrentUser) : new HyperLink[0],
                oneNoteUrl      = (await notebook) != null ? (await notebook).Url : "",
                oneNotePages    = await pages,
                conversations   = await groupConversations
            };

            return(viewModel);
        }
        //public async Task CreateTaskAsync(Graph.GraphService graphService, CreateTaskViewModel model)
        //{
        //    var inspection = await GetInspectionById(model.InspectionId);
        //    var property = inspection.sl_propertyID;

        //    var unifiedGroupFetcher = graphService.groups.GetById(property.sl_group);
        //    var unifiedGroup = await unifiedGroupFetcher.ExecuteAsync();

        //    var task = new Graph.Task
        //    {
        //        title = model.Title,
        //        percentComplete = 0,
        //        startDate = inspection.sl_datetime,
        //        dueDate = inspection.sl_datetime,
        //        // TODO: description = model.Description,
        //    };
        //    await unifiedGroupFetcher.tasks.AddTaskAsync(task);
        //}

        public async Task <string> AnnotateImagesAsync(Graph.GraphService graphService, OneNoteServiceFactory oneNoteServiceFactory, string siteRootDirectory, int incidentId)
        {
            var getIncident    = GetIncidentByIdAsync(incidentId);
            var incidentVideos = GetVideosAsync(AppSettings.VideoPortalIncidentsChannelName, incidentId);

            var incident = await getIncident;
            var property = incident.sl_propertyID;

            var unifiedGroupFetcher = graphService.groups.GetById(property.sl_group);
            var unifiedGroup        = unifiedGroupFetcher.ExecuteAsync();

            var oneNoteService = await oneNoteServiceFactory.CreateOneNoteServiceForUnifiedGroup(await unifiedGroup);

            var notebookName = (await unifiedGroup).displayName + " Notebook";
            var sectionId    = await GetOrCreateNoteBook(oneNoteService, notebookName)
                               .ContinueWith(async task =>
            {
                var _notebookId = task.Result.Id;
                var _sectionId  = await oneNoteService.GetSectionIdAsync(_notebookId, property.Title);
                if (_sectionId == null)
                {
                    _sectionId = await oneNoteService.CreateSectionAsync(_notebookId, property.Title);
                }
                return(_sectionId);
            });

            var inspectionPhotos = GetInspectionOrRepairPhotosAsync("Room Inspection Photos", incident.sl_inspectionIDId.Value, incident.sl_roomID.Id);

            var pageUrl = await oneNoteService.CreatePageForIncidentAsync(siteRootDirectory, await sectionId, incident, await inspectionPhotos, await incidentVideos);

            return(pageUrl);
        }
        public async Task<ActionResult> AnnotateImages(int incidentId)
        {
            var sharePointToken = AuthenticationHelper.GetAccessTokenAsync(AppSettings.DemoSiteServiceResourceId);
            var oneNoteToken = AuthenticationHelper.GetOneNoteAccessTokenAsync();

            var graphService = AuthenticationHelper.GetGraphServiceAsync();
            var dashboardService = new Dashboard(await sharePointToken);

            var oneNoteServiceFactory = new OneNoteServiceFactory(AADAppSettings.OneNoteResourceUrl, await oneNoteToken);
            var pageUrl = await dashboardService.AnnotateImagesAsync(await graphService, oneNoteServiceFactory, Server.MapPath("/"), incidentId);
            return Redirect(pageUrl);
        }
        public async Task<DashboardInspectionDetailsViewModel> GetDashboardInspectionDetailsViewModelAsync(Graph.GraphService graphService, OneNoteServiceFactory oneNoteServiceFactory, int incidentId, string CurrentUser)
        {
            Task<Graph.IUser[]> getRepairPeople = null;
            Task<RepairPhoto[]> getRepairPhotos = null;

            var videos = GetVideosAsync(AppSettings.VideoPortalIncidentsChannelName, incidentId);

            var incident = await GetIncidentByIdAsync(incidentId);
            if (incident.sl_inspectionIDId == null) return null;

            var property = incident.sl_propertyID;
            var propertyImgUrl = GetPropertyPhotoAsync(property.Id);

            var inspectionID = incident.sl_inspectionIDId.Value;
            var inspection = GetInspectionByIdAsync(inspectionID);
            var getInspectionPhotos = GetInspectionPhotosAsync(inspectionID);

            var incidentStatus = incident.sl_status;
            if (incidentStatus == "Pending Assignment")
                getRepairPeople = graphService.GetGroupMembersAsync("Repair People");
            if (incidentStatus == "Repair Pending Approval" || incidentStatus == "Repair Approved")
                getRepairPhotos = GetRepairPhotosAsync(incidentId);

            var unifiedGroupFetcher = graphService.groups.GetById(property.sl_group);
            var unifiedGroup = unifiedGroupFetcher.ExecuteAsync();
            var groupFiles = GetGroupFilesAsync(unifiedGroupFetcher, (await unifiedGroup).mailNickname);
            var groupConversations = GetConversationsAsync(unifiedGroupFetcher, (await unifiedGroup).mail);

            var notebookName = (await unifiedGroup).displayName + " Notebook"; ;
            var oneNoteService = oneNoteServiceFactory.CreateOneNoteServiceForUnifiedGroup(await unifiedGroup);
            var notebook = GetOrCreateNoteBook(await oneNoteService, notebookName);
            var pages = (await notebook) != null
                ? GetOneNotePagesAsync(await oneNoteService, (await notebook).Id, property.Title, incidentId)
                : Task.FromResult(new HyperLink[0]);

            // Repair people are included in property group.
            // Before we get members of a group, we must make sure that repair people have been retrieved.
            // Otherwise, we'll get an error: 
            //         The context is already tracking a different entity with the same resource Uri.
            if (getRepairPeople != null) await getRepairPeople;
            var groupMembers = graphService.GetGroupMembersAsync(unifiedGroupFetcher);

            var recentEarliestDateTime = new DateTimeOffset(DateTime.UtcNow).AddDays(-7);
            var recentDocuments = (await groupFiles)
                .Where(i => i.dateTimeLastModified > recentEarliestDateTime)
                .ToList();

            property.propertyImgUrl = await propertyImgUrl;

            var isCurrentUserDispatcher = CurrentUser == AppSettings.DispatcherEmail;


            var viewModel = new DashboardInspectionDetailsViewModel
            {
                viewName = IncidentStatusViewMappings[incidentStatus],
                PropertyDetail = property,
                incidentId = incidentId,
                incident = incident,
                UnifiedGroupNickName = (await unifiedGroup).mailNickname,
                UnifiedGroupId = (await unifiedGroup).objectId,
                UnifiedGroupEmail = (await unifiedGroup).mail,
                inspection = await inspection,
                videos = await videos,
                files = (await groupFiles)
                    .Select(i => HyperLink.Create(i.name, i.webUrl))
                    .ToArray(),
                recentDocuments = recentDocuments
                    .Select(i => HyperLink.Create(i.name, i.webUrl))
                    .ToArray(),
                members = await groupMembers,
                roomInspectionPhotos = await getInspectionPhotos,
                inspectionComment = await GetInspectionCommentAsync(inspectionID, incident.sl_roomID.Id),
                //tasks = await GetTaskHyperLinksAsync(unifiedGroup)
                repairPeople = getRepairPeople != null ? await getRepairPeople : new Graph.IUser[0],
                repairPhotos = getRepairPhotos != null ? await getRepairPhotos : new RepairPhoto[0],
                DispatcherMails = isCurrentUserDispatcher ? await GetMailsForDispatcherAsync(graphService, CurrentUser) : new HyperLink[0],
                oneNoteUrl = (await notebook) != null ? (await notebook).Url : "",
                oneNotePages = await pages,
                conversations = await groupConversations
            };
            return viewModel;
        }
        //public async Task CreateTaskAsync(Graph.GraphService graphService, CreateTaskViewModel model)
        //{
        //    var inspection = await GetInspectionById(model.InspectionId);
        //    var property = inspection.sl_propertyID;

        //    var unifiedGroupFetcher = graphService.groups.GetById(property.sl_group);
        //    var unifiedGroup = await unifiedGroupFetcher.ExecuteAsync();

        //    var task = new Graph.Task
        //    {
        //        title = model.Title,
        //        percentComplete = 0,
        //        startDate = inspection.sl_datetime,
        //        dueDate = inspection.sl_datetime,
        //        // TODO: description = model.Description,
        //    };
        //    await unifiedGroupFetcher.tasks.AddTaskAsync(task);
        //}

        public async Task<string> AnnotateImagesAsync(Graph.GraphService graphService, OneNoteServiceFactory oneNoteServiceFactory, string siteRootDirectory, int incidentId)
        {
            var getIncident = GetIncidentByIdAsync(incidentId);
            var incidentVideos = GetVideosAsync(AppSettings.VideoPortalIncidentsChannelName, incidentId);

            var incident = await getIncident;
            var property = incident.sl_propertyID;

            var unifiedGroupFetcher = graphService.groups.GetById(property.sl_group);
            var unifiedGroup = unifiedGroupFetcher.ExecuteAsync();

            var oneNoteService = await oneNoteServiceFactory.CreateOneNoteServiceForUnifiedGroup(await unifiedGroup);

            var notebookName = (await unifiedGroup).displayName + " Notebook";
            var sectionId = await GetOrCreateNoteBook(oneNoteService, notebookName)
                .ContinueWith(async task =>
                {
                    var _notebookId = task.Result.Id;
                    var _sectionId = await oneNoteService.GetSectionIdAsync(_notebookId, property.Title);
                    if (_sectionId == null)
                        _sectionId = await oneNoteService.CreateSectionAsync(_notebookId, property.Title);
                    return _sectionId;
                });

            var inspectionPhotos = GetInspectionOrRepairPhotosAsync("Room Inspection Photos", incident.sl_inspectionIDId.Value, incident.sl_roomID.Id);

            var pageUrl = await oneNoteService.CreatePageForIncidentAsync(siteRootDirectory, await sectionId, incident, await inspectionPhotos, await incidentVideos);

            return pageUrl;
        }