public async Task UpdateSchedulesAsync(IEnumerable <IScheduleGroup> groups, DayOfWeek day) { var validated = ValidateGroups(groups); var tfresh = Task.Run(() => freshInfoProvider.GetSchedules(validated, day)); var tstored = Task.Run(() => storage.GetSchedules(validated, day)); await Task.WhenAll(tfresh, tstored); //sync, already completed var fresh = await tfresh; var stored = await tstored; var goodFresh = fresh.Where(schedule => { var checkresult = schedule.ScheduleRoot.CheckElemIsCorrect(); if (!checkresult.Successed) { foreach (var error in checkresult.ErrorsList) { logger?.LogWarning("WHILE CHECK FRESH SCHEDULE ERROR FOUND:" + error); } } //return checkresult.Successed; return(true); }); List <Task> updateTasks = new List <Task>(); //full outher join fresh <-> stored by group foreach (var entry in goodFresh.Select(f => new { Group = f.ScheduleGroups.FirstOrDefault(), IsFresh = true, Root = f.ScheduleRoot }) .Concat(stored.Select(s => new { Group = s.ScheduleGroups.FirstOrDefault(), IsFresh = false, Root = s.ScheduleRoot })) .GroupBy(sch => sch.Group)) { var freshSch = entry.FirstOrDefault(x => x.IsFresh); var storedSch = entry.FirstOrDefault(x => !x.IsFresh); if (freshSch != null) { updateTasks.Add(CompareAndAddIfNotEqual(freshSch.Root, storedSch?.Root, entry.Key)); } else { updateTasks.Add(storage.RemoveScheduleAsync(entry.Key, day).ContinueWith(t => entry.Key.RaiseScheduleChanged(this, eventArgsFactory.GetArgs(storedSch.Root)))); } } await Task.WhenAll(updateTasks); Task CompareAndAddIfNotEqual(IScheduleElem freshSchedule, IScheduleElem storedSchedule, IScheduleGroup group) { if (storedSchedule == null || !freshSchedule.Equals(storedSchedule)) { return(storage.UpdateScheduleAsync(group, freshSchedule).ContinueWith((t) => group.RaiseScheduleChanged(this, eventArgsFactory.GetArgs(freshSchedule)))); } return(Task.CompletedTask); } }
public async Task UpdateStorage_WhenStorageDoesNotContainScheduleAndUpdateCalled() { var diffGroup = groups.Except(storedDays.Select(d => d.ScheduleGroups.FirstOrDefault())).FirstOrDefault(); var rootToUpd = freshDays.FirstOrDefault(d => d.ScheduleGroups.FirstOrDefault().Equals(diffGroup)) .ScheduleRoot; //act await service.UpdateSchedulesAsync(groups, 0); //assert A.CallTo(() => storageFake.UpdateScheduleAsync(diffGroup, rootToUpd)).MustHaveHappened(); }