private void generateSchedule(object sender, EventArgs e) { database db = new database(); List <string> courseID = new List <string>(); string query = "select * from selection"; DataTable dt = db.Table(query); int len = dt.Rows.Count; if (len == 0) { MessageBox.Show("Please select the courses you want to take..!"); return; } routine[] selectedCourses = new routine[len]; for (int i = 0; i < dt.Rows.Count; i++) { courseID.Add(dt.Rows[i]["id"].ToString()); } for (int i = 0; i < len; i++) { selectedCourses[i] = prepareSchedule.addSpecificCourse(courseID[i]); } routine recursiveScheduleMaker = new routine(); recursiveScheduleMaker.courses = new List <course>(); prepareSchedule.combinationalSchedules = null; prepareSchedule.combinationalSchedules = new List <routine>(); prepareSchedule.MakeMySchedule(0, selectedCourses, recursiveScheduleMaker); int generatedRoutines = prepareSchedule.combinationalSchedules.Count; if (generatedRoutines != 0) { this.Hide(); } if (generatedRoutines == 0) { MessageBox.Show("No routines can be generated"); return; } else if (prepareSchedule.combinationalSchedules[0].courses.Count > 5) { new resultsForMore(1, null, this, username).ShowDialog(); } else { new scheduleResults(1, null, this, username).ShowDialog(); } this.uncheckAllCheckBoxesPrev(); this.uncheckAllCheckBoxesFurther(); query = "delete from selection"; db.update(query); }
private void PopulateRoutine(routine routine, int routineIdx, StackLayout stackLayout) { int stackLayoutIdx = stackLayout.Children.Count; StackLayout itemStackLayout = new StackLayout() { Orientation = StackOrientation.Horizontal }; Frame frame = new Frame { CornerRadius = 10, HasShadow = false, HorizontalOptions = LayoutOptions.FillAndExpand, Padding = new Thickness(10, 10, 10, 10), Margin = new Thickness(0, 2, 0, 2) }; StackLayout stackLayoutOuter = new StackLayout { Orientation = StackOrientation.Horizontal }; StackLayout stackLayoutInner = new StackLayout { HorizontalOptions = LayoutOptions.StartAndExpand, }; Label routineTitleLabel = new Label { Text = routine.title, FontSize = 20, VerticalOptions = LayoutOptions.Start, FontFamily = labelFont }; Label startTimeLabel = new Label { Text = "Starts at " + DateTime.ParseExact(routine.availableStartTime.ToString(), "HH:mm:ss", null).ToString("hh:mm tt", CultureInfo.GetCultureInfo("en-US")), FontSize = 10, TextColor = Color.DimGray, VerticalOptions = LayoutOptions.EndAndExpand, FontFamily = labelFont }; Label expectedTimeLabel = new Label { Text = "Expected to take " + routine.expectedCompletionTime.TotalMinutes.ToString() + " minutes", FontSize = 10, TextColor = Color.DimGray, VerticalOptions = LayoutOptions.StartAndExpand, FontFamily = labelFont }; CachedImage image = new CachedImage() { Source = routine.photo, WidthRequest = 50, HeightRequest = 50, HorizontalOptions = LayoutOptions.End, Transformations = new List <ITransformation>() { new CircleTransformation(), }, }; var indicator = new ActivityIndicator { Color = Color.Gray, }; indicator.SetBinding(ActivityIndicator.IsRunningProperty, "IsLoading"); indicator.BindingContext = image; stackLayoutInner.Children.Add(routineTitleLabel); stackLayoutInner.Children.Add(startTimeLabel); stackLayoutInner.Children.Add(expectedTimeLabel); stackLayoutOuter.Children.Add(stackLayoutInner); stackLayoutOuter.Children.Add(image); frame.Content = stackLayoutOuter; CachedImage checkmarkImage = new CachedImage() { Source = "", WidthRequest = 0, HeightRequest = 0, IsVisible = false, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.CenterAndExpand }; if (routine.isComplete || routine.isInProgress) { checkmarkImage.IsVisible = true; if (routine.isInProgress) { checkmarkImage.Source = "yellowclockicon.png "; } else { if (routine.isComplete) { checkmarkImage.Source = "greencheckmarkicon.png"; } } checkmarkImage.WidthRequest = 30; checkmarkImage.HeightRequest = 30; } itemStackLayout.Children.Add(checkmarkImage); itemStackLayout.Children.Add(frame); stackLayout.Children.Add(itemStackLayout); var tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += async(s, e) => { StackLayout updatedStackLayout = (StackLayout)s; updatedStackLayout.Children[0].WidthRequest = 30; updatedStackLayout.Children[0].HeightRequest = 30; ((CachedImage)updatedStackLayout.Children[0]).IsVisible = true; if (routine.isSublistAvailable) { if (!routine.isInProgress) { ((CachedImage)updatedStackLayout.Children[0]).Source = "yellowclockicon.png"; routine.isInProgress = true; firebaseFunctionsService.startGR(routine.id.ToString(), routine.dbIdx.ToString()); App.ListPageScrollPosY = mainScrollView.ScrollY; } await Navigation.PushAsync(new TaskPage(routineIdx, true)); } else { if (!routine.isComplete) { if (routine.isInProgress) { ((CachedImage)updatedStackLayout.Children[0]).Source = "greencheckmarkicon.png"; routine.isInProgress = false; routine.isComplete = true; firebaseFunctionsService.CompleteRoutine(routine.id.ToString(), routine.dbIdx.ToString()); } else { ((CachedImage)updatedStackLayout.Children[0]).Source = "yellowclockicon.png"; routine.isInProgress = true; firebaseFunctionsService.startGR(routine.id.ToString(), routine.dbIdx.ToString()); } } } }; stackLayout.Children[stackLayoutIdx].GestureRecognizers.Add(tapGestureRecognizer); }
public GoalsRoutinesTemplateViewModel(GoalsRoutinesTemplate mainPage) { this.mainPage = mainPage; firebaseFunctionsService = new FirebaseFunctionsService(); setUpTime(); complete = new List <bool>(); Items = new ObservableCollection <GRItemModel>(); int itemCount = 0; int eventNum = 0; int routineNum = 0; int goalNum = 0; Items.Add(new GRItemModel( App.User.Me.pic, "About Me", Color.Default, Color.Black, new DateTime(1, 1, 1), "Tap to Learn More", App.User.Me.message_day, true ? .6 : 1, false, false, new Command <MyDayIndexes>( async(MyDayIndexes indexes) => { await mainPage.Navigation.PushAsync(new GreetingPage()); }), new MyDayIndexes(itemCount, eventNum, 0) )); itemCount++; eventNum++; List <object> list = new List <object>(); foreach (EventsItems calendarEvent in App.User.CalendarEvents) { list.Add(calendarEvent); } foreach (routine routine in App.User.routines) { list.Add(routine); } foreach (goal goal in App.User.goals) { list.Add(goal); } //insertion sort, sort events,routines,and goals by start time. for (int j = 0; j < list.Count; j++) { DateTime start; if (list[j].GetType().Name == "routine") { routine routine = (routine)list[j]; start = DateTime.Now.Date + routine.availableStartTime; } else if (list[j].GetType().Name == "goal") { goal goal = (goal)list[j]; start = DateTime.Now.Date + goal.availableStartTime; } else { EventsItems item = (EventsItems)list[j]; start = item.Start.DateTime.DateTime; } //int swap = 0; object temp = list[j]; object min = list[j]; int swap = j; for (int i = j + 1; i < list.Count; i++) { DateTime start2; if (list[i].GetType().Name == "routine") { routine routine2 = (routine)list[i]; start2 = DateTime.Now.Date + routine2.availableStartTime; } else if (list[i].GetType().Name == "goal") { goal goal2 = (goal)list[i]; start2 = DateTime.Now.Date + goal2.availableStartTime; } else { EventsItems item2 = (EventsItems)list[i]; start2 = item2.Start.DateTime.DateTime; } if (start.CompareTo(start2) > 0) { start = start2; min = list[i]; swap = i; } } list[swap] = temp; list[j] = min; } //generate items to card view. foreach (object obj in list) { if (obj.GetType().Name == "routine") { routine routine = (routine)obj; //calculate the sum duration for the routine from step level. if (routine.isSublistAvailable == true) { int sum_duration = 0; foreach (task task in routine.tasks) { if (task.isSublistAvailable == true) { int step_duration = 0; foreach (step step in task.steps) { step_duration += (int)step.expectedCompletionTime.TotalMinutes; } if (step_duration == 0) { sum_duration += (int)task.expectedCompletionTime.TotalMinutes; } else { sum_duration += step_duration; } } else { sum_duration += (int)task.expectedCompletionTime.TotalMinutes; } } // update the duration for routine if (sum_duration != 0) { routine.expectedCompletionTime = TimeSpan.FromMinutes(sum_duration); } } if (isInTimeRange(routine.availableStartTime, routine.availableEndTime)) { string buttonText = "Tap to Start"; if (routine.isInProgress) { buttonText = "Tap to Continue"; } else if (routine.isComplete) { buttonText = "Done"; } DateTime startTime = DateTime.Now.Date + routine.availableStartTime; complete.Add(false); Items.Add(new GRItemModel( routine.photo, routine.title, Color.Default, Color.Black, startTime, buttonText, "Expected to take " + routine.expectedCompletionTime.TotalMinutes + " minutes", (routine.isComplete || routine.isInProgress) ? .6 : 1, routine.isComplete, routine.isInProgress, new Command <MyDayIndexes>( async(MyDayIndexes indexes) => { string routineId = App.User.routines[indexes.RoutineIndex].id; string routineDbIdx = App.User.routines[indexes.RoutineIndex].dbIdx.ToString(); bool isRoutineInProgress = App.User.routines[indexes.RoutineIndex].isInProgress; bool isRoutineComplete = App.User.routines[indexes.RoutineIndex].isComplete; ((GRItemModel)Items[indexes.ItemsIndex]).GrImageOpactiy = .6; if (App.User.routines[indexes.RoutineIndex].isSublistAvailable) { if (!isRoutineComplete) { App.User.routines[indexes.RoutineIndex].isInProgress = true; ((GRItemModel)Items[indexes.ItemsIndex]).IsInProgress = true; ((GRItemModel)Items[indexes.ItemsIndex]).Text = "Tap to Continue"; firebaseFunctionsService.startGR(routineId, routineDbIdx); } await mainPage.Navigation.PushAsync(new TaskPage(indexes.RoutineIndex, true, (GRItemModel)Items[indexes.ItemsIndex])); } else { if (!isRoutineComplete) { if (isRoutineInProgress) { App.User.routines[indexes.RoutineIndex].isInProgress = false; App.User.routines[indexes.RoutineIndex].isComplete = true; ((GRItemModel)Items[indexes.ItemsIndex]).IsInProgress = false; ((GRItemModel)Items[indexes.ItemsIndex]).IsComplete = true; ((GRItemModel)Items[indexes.ItemsIndex]).Text = "Done"; firebaseFunctionsService.CompleteRoutine(routineId, routineDbIdx); } else { App.User.routines[indexes.RoutineIndex].isInProgress = true; ((GRItemModel)Items[indexes.ItemsIndex]).IsInProgress = true; ((GRItemModel)Items[indexes.ItemsIndex]).Text = "Tap to Continue"; firebaseFunctionsService.startGR(routineId, routineDbIdx); } } } }), new MyDayIndexes(itemCount, routineNum, 0) )); itemCount++; } routineNum++; } else if (obj.GetType().Name == "goal") { goal goal = (goal)obj; //calculate the sum duration for the goal from instruction level. if (goal.isSublistAvailable == true) { int goal_duration = 0; foreach (action action in goal.actions) { if (action.isSublistAvailable == true) { int instruction_duration = 0; foreach (instruction instruction in action.instructions) { instruction_duration += (int)instruction.expectedCompletionTime.TotalMinutes; } if (instruction_duration == 0) { goal_duration += (int)action.expectedCompletionTime.TotalMinutes; } else { goal_duration += instruction_duration; } } else { goal_duration += (int)action.expectedCompletionTime.TotalMinutes; } } // update the duration for goal if (goal_duration != 0) { goal.expectedCompletionTime = TimeSpan.FromMinutes(goal_duration); } } if (isInTimeRange(goal.availableStartTime, goal.availableEndTime)) { string buttonText = "Tap to Start"; if (goal.isInProgress) { buttonText = "Tap to Continue"; } else if (goal.isComplete) { buttonText = "Done"; } DateTime startTime = DateTime.Now.Date + goal.availableStartTime; complete.Add(false); Items.Add(new GRItemModel( goal.photo, goal.title, Color.FromHex("#272E32"), Color.White, startTime, buttonText, "Expected to take " + goal.expectedCompletionTime.TotalMinutes + " minutes", (goal.isComplete || goal.isInProgress) ? .6 : 1, goal.isComplete, goal.isInProgress, new Command <MyDayIndexes>( async(MyDayIndexes indexes) => { string goalId = App.User.goals[indexes.GoalIndex].id; string goalDbIdx = App.User.goals[indexes.GoalIndex].dbIdx.ToString(); bool isGoalInProgress = App.User.goals[indexes.GoalIndex].isInProgress; bool isGoalComplete = App.User.goals[indexes.GoalIndex].isComplete; ((GRItemModel)Items[indexes.ItemsIndex]).GrImageOpactiy = .6; if (App.User.goals[indexes.GoalIndex].isSublistAvailable) { if (!isGoalComplete) { App.User.goals[indexes.GoalIndex].isInProgress = true; ((GRItemModel)Items[indexes.ItemsIndex]).Text = "Tap to Continue"; ((GRItemModel)Items[indexes.ItemsIndex]).IsInProgress = true; firebaseFunctionsService.startGR(goalId, goalDbIdx); } await mainPage.Navigation.PushAsync(new TaskPage(indexes.GoalIndex, false, (GRItemModel)Items[indexes.ItemsIndex])); } else { if (!isGoalComplete) { if (isGoalInProgress) { App.User.goals[indexes.GoalIndex].isInProgress = false; App.User.goals[indexes.GoalIndex].isComplete = true; ((GRItemModel)Items[indexes.ItemsIndex]).IsInProgress = false; ((GRItemModel)Items[indexes.ItemsIndex]).IsComplete = true; ((GRItemModel)Items[indexes.ItemsIndex]).Text = "Done"; firebaseFunctionsService.CompleteRoutine(goalId, goalDbIdx); } else { App.User.goals[indexes.GoalIndex].isInProgress = true; ((GRItemModel)Items[indexes.ItemsIndex]).IsInProgress = true; ((GRItemModel)Items[indexes.ItemsIndex]).Text = "Tap to Continue"; firebaseFunctionsService.startGR(goalId, goalDbIdx); } } } }), new MyDayIndexes(itemCount, 0, goalNum) )); itemCount++; } goalNum++; } else { EventsItems calendarEvent = (EventsItems)obj; Items.Add(new GRItemModel( "eventIcon.jpg", calendarEvent.EventName, Color.Goldenrod, Color.Black, calendarEvent.Start.DateTime.DateTime, calendarEvent.Description, "Start Time: " + calendarEvent.Start.DateTime.TimeOfDay + "\n" + "End Time: " + calendarEvent.End.DateTime.TimeOfDay + "", true ? .6 : 1, false, true, new Command <MyDayIndexes>( async(MyDayIndexes indexes) => { }), new MyDayIndexes(itemCount, eventNum, 0) )); itemCount++; eventNum++; } } }
public async Task LoadUser() { Console.WriteLine("In Load User"); // reset current user and goals values (in case of reload) App.User.routines = new List <routine>(); App.User.goals = new List <goal>(); var request = new HttpRequestMessage { RequestUri = new Uri("https://firestore.googleapis.com/v1/projects/project-caitlin-c71a9/databases/(default)/documents/users/" + uid), Method = HttpMethod.Get }; var client = new HttpClient(); HttpResponseMessage response = await client.SendAsync(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { HttpContent content = response.Content; var userResponse = await content.ReadAsStringAsync(); JObject userJson = JObject.Parse(userResponse); // About me JToken userAboutMe; try { userAboutMe = userJson["fields"]["about_me"]["mapValue"]["fields"]; if (userAboutMe == null) { return; } } catch { //Console.WriteLine("Error with json goal/routine token:"); //Console.WriteLine(userJson); return; } App.User.Me.have_pic = (bool)userAboutMe["have_pic"]["booleanValue"]; App.User.Me.message_day = userAboutMe["message_day"]["stringValue"].ToString(); App.User.Me.message_card = userAboutMe["message_card"]["stringValue"].ToString(); App.User.Me.pic = userAboutMe["pic"]["stringValue"].ToString(); //int peopleIdx = 0; if (userAboutMe["important_people"] != null) { foreach (JToken jsonPeople in userAboutMe["important_people"]["arrayValue"]["values"]) { try { String people_id = jsonPeople["referenceValue"].ToString(); // Console.WriteLine(jsonPeople["referenceValue"]); var request_people = new HttpRequestMessage { RequestUri = new Uri("https://firestore.googleapis.com/v1/" + people_id), Method = HttpMethod.Get }; var client_people = new HttpClient(); HttpResponseMessage response_people = await client.SendAsync(request_people); if (response_people.StatusCode == System.Net.HttpStatusCode.OK) { HttpContent content_people = response_people.Content; var peopleResponse = await content_people.ReadAsStringAsync(); JObject peopleJson = JObject.Parse(peopleResponse); people people = new people(); people.have_pic = (bool)peopleJson["fields"]["have_pic"]["booleanValue"]; people.name = peopleJson["fields"]["name"]["stringValue"].ToString(); people.phone_number = peopleJson["fields"]["phone_number"]["stringValue"].ToString(); people.pic = peopleJson["fields"]["pic"]["stringValue"].ToString(); people.unique_id = peopleJson["fields"]["unique_id"]["stringValue"].ToString(); //Console.WriteLine("People values"); App.User.Me.peoples.Add(people); /*Console.WriteLine("People Values"); * Console.WriteLine(peopleJson["fields"]["name"]["stringValue"].ToString()); * Console.WriteLine(peopleJson["createTime"]);*/ } } catch { } } } // Goals and routines JToken userJsonGoalsAndRoutines; try { userJsonGoalsAndRoutines = userJson["fields"]["goals&routines"]["arrayValue"]["values"]; if (userJsonGoalsAndRoutines == null) { return; } } catch { //Console.WriteLine("Error with json goal/routine token:"); //Console.WriteLine(userJson); return; } App.User.firstName = userJson["fields"]["first_name"]["stringValue"].ToString(); App.User.lastName = userJson["fields"]["last_name"]["stringValue"].ToString(); TimeSpan currentTime = DateTime.Now.TimeOfDay; int dbIdx_ = 0; int routineIdx = 0; int goalIdx = 0; foreach (JToken jsonGorR in userJsonGoalsAndRoutines) { try { JToken jsonMapGorR = jsonGorR["mapValue"]["fields"]; Console.WriteLine("routine: " + jsonMapGorR["title"]["stringValue"].ToString()); var isDeleted = false; if (jsonMapGorR["deleted"] != null) { if ((bool)jsonMapGorR["deleted"]["booleanValue"]) { isDeleted = true; } } if ((bool)jsonMapGorR["is_available"]["booleanValue"] && !isDeleted) { bool isInProgressCheck = (jsonMapGorR["is_in_progress"] == null) ? false : (bool)jsonMapGorR["is_in_progress"]["booleanValue"]; if ((bool)jsonMapGorR["is_persistent"]["booleanValue"]) { routine routine = new routine { title = jsonMapGorR["title"]["stringValue"].ToString(), id = jsonMapGorR["id"]["stringValue"].ToString(), photo = jsonMapGorR["photo"]["stringValue"].ToString(), isInProgress = isInProgressCheck && IsDateToday(jsonMapGorR["datetime_started"]["stringValue"].ToString()), isComplete = (bool)jsonMapGorR["is_complete"]["booleanValue"] && IsDateToday(jsonMapGorR["datetime_completed"]["stringValue"].ToString()) && !isInProgressCheck, expectedCompletionTime = TimeSpan.Parse(jsonMapGorR["expected_completion_time"]["stringValue"].ToString()), dbIdx = dbIdx_, isSublistAvailable = (bool)jsonMapGorR["is_sublist_available"]["booleanValue"], dateTimeCompleted = DateTime.Parse(jsonMapGorR["datetime_completed"]["stringValue"].ToString()).ToLocalTime(), availableStartTime = TimeSpan.Parse(jsonMapGorR["available_start_time"]["stringValue"].ToString()), availableEndTime = TimeSpan.Parse(jsonMapGorR["available_end_time"]["stringValue"].ToString()) }; //time precised in minutes, can be positive or negative. int startTime = (int)(currentTime - routine.availableStartTime).TotalMinutes; int endTime = (int)(currentTime - routine.availableEndTime).TotalMinutes; JToken userNotification; try { //Console.WriteLine("jsonMapGorR" + jsonMapGorR["user_notifications"]["mapValue"]["fields"]); userNotification = jsonMapGorR["user_notifications"]["mapValue"]["fields"]; if (userNotification == null) { return; } routine.Notification = new Notification(); routine.Notification.user = new NotificationTime(); JToken userBefore = userNotification["before"]; JToken userBeforeMap = userBefore["mapValue"]["fields"]; routine.Notification.user.before.is_set = (bool)userBeforeMap["is_set"]["booleanValue"] && ((userBeforeMap["date_set"] != null) ? IsDateToday(userBeforeMap["date_set"]["stringValue"].ToString()) : false); routine.Notification.user.before.is_enabled = (bool)userBeforeMap["is_enabled"]["booleanValue"]; if (routine.Notification.user.before.is_enabled && !routine.Notification.user.before.is_set) { routine.Notification.user.before.time = TimeSpan.Parse(userBeforeMap["time"]["stringValue"].ToString()); //TotalMinutes double total = routine.Notification.user.before.time.TotalSeconds - (routine.availableStartTime - DateTime.Now.TimeOfDay).TotalSeconds; //routine.Notification.user.before.message = userBefore["message"]["stringValue"].ToString(); if (!routine.isComplete && total > 0 && !routine.Notification.user.before.is_set) { notificationManager.ScheduleNotification(routineIdx + "Ready for ", routine.title + "? Open the app to review your tasks." + routine.Notification.user.before.message, total); firebaseFunctionsService.GRUserNotificationSetToTrue(routine.id, routine.dbIdx.ToString(), "before"); } Console.WriteLine("total : " + total); Console.WriteLine("before message: " + routine.Notification.user.before.message); } JToken userDuring = userNotification["during"]; JToken userDuringMap = userDuring["mapValue"]["fields"]; routine.Notification.user.during.is_set = (bool)userDuringMap["is_set"]["booleanValue"] && (userDuringMap["date_set"] != null) ? IsDateToday(userDuringMap["date_set"]["stringValue"].ToString()) : false; routine.Notification.user.during.is_enabled = (bool)userDuringMap["is_enabled"]["booleanValue"]; if (routine.Notification.user.during.is_enabled && !routine.Notification.user.during.is_set) { routine.Notification.user.during.time = TimeSpan.Parse(userDuringMap["time"]["stringValue"].ToString()); //TotalMinutes double total = routine.Notification.user.during.time.TotalSeconds + (routine.availableStartTime - DateTime.Now.TimeOfDay).TotalSeconds; routine.Notification.user.during.message = userDuringMap["message"]["stringValue"].ToString(); if (!routine.isComplete && total > 0 && !routine.Notification.user.during.is_set) { notificationManager.ScheduleNotification(routineIdx + "Time for ", routine.title + ". Open the app to review your tasks." + routine.Notification.user.during.message, total); firebaseFunctionsService.GRUserNotificationSetToTrue(routine.id, routine.dbIdx.ToString(), "during"); } Console.WriteLine("total : " + total); Console.WriteLine("during message: " + routine.Notification.user.during.message); } JToken userAfter = userNotification["after"]; JToken userAfterMap = userAfter["mapValue"]["fields"]; Console.WriteLine("userAfterMap" + userAfterMap); // is_set to make sure notification is not already stored on phone routine.Notification.user.after.is_set = (bool)userAfterMap["is_set"]["booleanValue"] && (userAfterMap["date_set"] != null) ? IsDateToday(userAfterMap["date_set"]["stringValue"].ToString()) : false; routine.Notification.user.during.is_enabled = (bool)userDuringMap["is_enabled"]["booleanValue"]; if (routine.Notification.user.during.is_enabled && !routine.Notification.user.after.is_set) { routine.Notification.user.after.time = TimeSpan.Parse(userAfterMap["time"]["stringValue"].ToString()); //TotalMinutes double total = routine.Notification.user.after.time.TotalSeconds + (routine.availableEndTime - DateTime.Now.TimeOfDay).TotalSeconds; routine.Notification.user.after.message = userAfterMap["message"]["stringValue"].ToString(); if (!routine.isComplete && total > 0 && !routine.Notification.user.after.is_set) { notificationManager.ScheduleNotification(routineIdx + "You Missed a Routine! ", routine.title + " is overdue. Open the app to review your tasks." + routine.Notification.user.after.message, total); firebaseFunctionsService.GRUserNotificationSetToTrue(routine.id, routine.dbIdx.ToString(), "after"); } Console.WriteLine("total : " + total); Console.WriteLine("after message: " + routine.Notification.user.after.message); } } catch (Exception e) { Console.WriteLine("NOTIFICATION ERROR"); Console.WriteLine("{0} Exception caught.", e); } notificationManager.PrintPendingNotifications(); /* * Console.WriteLine("start time : " + startTime); * Console.WriteLine("end time : " + endTime); * if (startTime < 0 && startTime > total) * notificationManager.ScheduleNotification("You Missed a Routine! ", routine.title + " is overdue. Open the app to review your tasks.", 1); * if (!routine.isComplete && endTime > 0 && endTime < 30 ) * notificationManager.ScheduleNotification("You Missed a Routine! ", routine.title + " is overdue. Open the app to review your tasks.", 1); * else if (!routine.isComplete && currentTime > routine.availableStartTime && currentTime < routine.availableEndTime) * notificationManager.ScheduleNotification("Time for ", routine.title + ". Open the app to review your tasks.", 1); * */ /*JToken userNotification; * try * { * userNotification = jsonGorR["fields"]["ta_notifications"]["arrayValue"]["values"]; * if (userNotification == null) * return; * } * catch * { * return; * }*/ /* if (!(bool)jsonMapGorR["user_notification_set"]["booleanValue"] * && (bool)jsonMapGorR["reminds_user"]["booleanValue"] * ) * { * if (firebaseFunctionsService.GRUserNotificationSetToTrue(routine.id, routine.dbIdx.ToString()).Result) * { * string title = "You Missed a Routine!"; * //double duration = (routine.availableEndTime.TimeOfDay - DateTime.Now.TimeOfDay).TotalSeconds; * double duration = 10; * string message = routine.title + " is overdue. Open the app to review your tasks."; * //Console.WriteLine("duration: " + duration); * if (duration > 0) * { * Console.WriteLine("notification id: " + notificationManager.ScheduleNotification(title, message, duration)); * } * } * }*/ /* * Console.WriteLine("start time : " + startTime); * Console.WriteLine("end time : " + endTime); * if (startTime < 0 && startTime > total) * notificationManager.ScheduleNotification("You Missed a Routine! ", routine.title + " is overdue. Open the app to review your tasks.", 1); * if (!routine.isComplete && endTime > 0 && endTime < 30 ) * notificationManager.ScheduleNotification("You Missed a Routine! ", routine.title + " is overdue. Open the app to review your tasks.", 1); * else if (!routine.isComplete && currentTime > routine.availableStartTime && currentTime < routine.availableEndTime) * notificationManager.ScheduleNotification("Time for ", routine.title + ". Open the app to review your tasks.", 1); * */ /*JToken userNotification; * try * { * userNotification = jsonGorR["fields"]["ta_notifications"]["arrayValue"]["values"]; * if (userNotification == null) * return; * } * catch * { * return; * }*/ /* if (!(bool)jsonMapGorR["user_notification_set"]["booleanValue"] * && (bool)jsonMapGorR["reminds_user"]["booleanValue"] * ) * { * if (firebaseFunctionsService.GRUserNotificationSetToTrue(routine.id, routine.dbIdx.ToString()).Result) * { * string title = "You Missed a Routine!"; * //double duration = (routine.availableEndTime.TimeOfDay - DateTime.Now.TimeOfDay).TotalSeconds; * double duration = 10; * string message = routine.title + " is overdue. Open the app to review your tasks."; * //Console.WriteLine("duration: " + duration); * if (duration > 0) * { * Console.WriteLine("notification id: " + notificationManager.ScheduleNotification(title, message, duration)); * } * } * }*/ App.User.routines.Add(routine); routineIdx++; //Console.WriteLine("on Routine: " + routine.title + " " + routine.id); } else { goal goal = new goal { title = jsonMapGorR["title"]["stringValue"].ToString(), id = jsonMapGorR["id"]["stringValue"].ToString(), photo = jsonMapGorR["photo"]["stringValue"].ToString(), isInProgress = isInProgressCheck && IsDateToday(jsonMapGorR["datetime_started"]["stringValue"].ToString()), isComplete = (bool)jsonMapGorR["is_complete"]["booleanValue"] && IsDateToday(jsonMapGorR["datetime_completed"]["stringValue"].ToString()) && !isInProgressCheck, dbIdx = dbIdx_, isSublistAvailable = (bool)jsonMapGorR["is_sublist_available"]["booleanValue"], expectedCompletionTime = TimeSpan.Parse(jsonMapGorR["expected_completion_time"]["stringValue"].ToString()), dateTimeCompleted = DateTime.Parse(jsonMapGorR["datetime_completed"]["stringValue"].ToString()).ToLocalTime(), availableStartTime = TimeSpan.Parse(jsonMapGorR["available_start_time"]["stringValue"].ToString()), availableEndTime = TimeSpan.Parse(jsonMapGorR["available_end_time"]["stringValue"].ToString()) }; App.User.goals.Add(goal); goalIdx++; ////Console.WriteLine("on Goal: " + goal.id); } } } catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); } dbIdx_++; } App.User.routines.Sort((x, y) => TimeSpan.Compare(x.availableStartTime, y.availableStartTime)); App.User.goals.Sort((x, y) => TimeSpan.Compare(x.availableStartTime, y.availableStartTime)); routineIdx = 0; foreach (routine routine in App.User.routines) { LoadTasks(routine.id, routineIdx, "routine"); routineIdx++; } goalIdx = 0; foreach (goal goal in App.User.goals) { LoadTasks(goal.id, goalIdx, "goal"); goalIdx++; } } }
public async Task LoadUser() { Console.WriteLine("In Load User"); // reset current user and goals values (in case of reload) App.User.routines = new List <routine>(); App.User.goals = new List <goal>(); App.User.photoURIs = new List <List <String> >(); App.User.allDates = new HashSet <string>(); //load photos. await LoadFirebasePhoto(); //move it to navbar click function. //await GooglePhotoService.GetPhotos(); var request = new HttpRequestMessage { RequestUri = new Uri("https://firestore.googleapis.com/v1/projects/project-caitlin-c71a9/databases/(default)/documents/users/" + uid), Method = HttpMethod.Get }; var client = new HttpClient(); HttpResponseMessage response = await client.SendAsync(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { HttpContent content = response.Content; var userResponse = await content.ReadAsStringAsync(); JObject userJson = JObject.Parse(userResponse); // About me JToken userAboutMe; try { userAboutMe = userJson["fields"]["about_me"]["mapValue"]["fields"]; if (userAboutMe == null) { return; } } catch { return; } App.User.Me.have_pic = (bool)userAboutMe["have_pic"]["booleanValue"]; App.User.Me.message_day = userAboutMe["message_day"]["stringValue"].ToString(); App.User.Me.message_card = userAboutMe["message_card"]["stringValue"].ToString(); App.User.Me.pic = userAboutMe["pic"]["stringValue"].ToString(); LoadPeople(); // Goals and routines JToken userJsonGoalsAndRoutines; try { userJsonGoalsAndRoutines = userJson["fields"]["goals&routines"]["arrayValue"]["values"]; if (userJsonGoalsAndRoutines == null) { return; } } catch { return; } App.User.firstName = userJson["fields"]["first_name"]["stringValue"].ToString(); App.User.lastName = userJson["fields"]["last_name"]["stringValue"].ToString(); TimeSpan currentTime = DateTime.Now.TimeOfDay; int dbIdx_ = 0; int routineIdx = 0; int goalIdx = 0; foreach (JToken jsonGorR in userJsonGoalsAndRoutines) { try { JToken jsonMapGorR = jsonGorR["mapValue"]["fields"]; Console.WriteLine("routine: " + jsonMapGorR["title"]["stringValue"].ToString()); var isDeleted = false; if (jsonMapGorR["deleted"] != null) { if ((bool)jsonMapGorR["deleted"]["booleanValue"]) { isDeleted = true; } } if ((bool)jsonMapGorR["is_available"]["booleanValue"] && !isDeleted) { bool isInProgressCheck = (jsonMapGorR["is_in_progress"] == null) ? false : (bool)jsonMapGorR["is_in_progress"]["booleanValue"]; if ((bool)jsonMapGorR["is_persistent"]["booleanValue"]) { routine routine = new routine { title = jsonMapGorR["title"]["stringValue"].ToString(), id = jsonMapGorR["id"]["stringValue"].ToString(), photo = jsonMapGorR["photo"]["stringValue"].ToString(), isInProgress = isInProgressCheck && IsDateToday(jsonMapGorR["datetime_started"]["stringValue"].ToString()), isComplete = (bool)jsonMapGorR["is_complete"]["booleanValue"] && IsDateToday(jsonMapGorR["datetime_completed"]["stringValue"].ToString()) && !isInProgressCheck, expectedCompletionTime = TimeSpan.Parse(jsonMapGorR["expected_completion_time"]["stringValue"].ToString()), dbIdx = dbIdx_, isSublistAvailable = (bool)jsonMapGorR["is_sublist_available"]["booleanValue"], dateTimeCompleted = DateTime.Parse(jsonMapGorR["datetime_completed"]["stringValue"].ToString()).ToLocalTime(), availableStartTime = TimeSpan.Parse(jsonMapGorR["available_start_time"]["stringValue"].ToString()), availableEndTime = TimeSpan.Parse(jsonMapGorR["available_end_time"]["stringValue"].ToString()) }; //time precised in minutes, can be positive or negative. int startTime = (int)(currentTime - routine.availableStartTime).TotalMinutes; int endTime = (int)(currentTime - routine.availableEndTime).TotalMinutes; JToken userNotification; try { //Console.WriteLine("jsonMapGorR" + jsonMapGorR["user_notifications"]["mapValue"]["fields"]); userNotification = jsonMapGorR["user_notifications"]["mapValue"]["fields"]; if (userNotification == null) { return; } routine.Notification = new Notification(); routine.Notification.user = new NotificationTime(); JToken userBefore = userNotification["before"]; JToken userBeforeMap = userBefore["mapValue"]["fields"]; routine.Notification.user.before.is_set = (bool)userBeforeMap["is_set"]["booleanValue"] && ((userBeforeMap["date_set"] != null) ? IsDateToday(userBeforeMap["date_set"]["stringValue"].ToString()) : false); routine.Notification.user.before.is_enabled = (bool)userBeforeMap["is_enabled"]["booleanValue"]; if (routine.Notification.user.before.is_enabled && !routine.Notification.user.before.is_set) { routine.Notification.user.before.time = TimeSpan.Parse(userBeforeMap["time"]["stringValue"].ToString()); //TotalMinutes double total = (routine.availableStartTime - DateTime.Now.TimeOfDay).TotalSeconds - routine.Notification.user.before.time.TotalSeconds; routine.Notification.user.before.message = userBeforeMap["message"]["stringValue"].ToString(); if (!routine.isComplete && total > 0 && !routine.Notification.user.before.is_set) { string title = "Ready for " + routine.title + "?"; string subtitle = routineIdx + routine.id; string message = "Open the app to review your tasks. " + routine.Notification.user.before.message; notificationManager.ScheduleNotification(title, subtitle, message, total); firebaseFunctionsService.GRUserNotificationSetToTrue(routine.id, routine.dbIdx.ToString(), "before"); } Console.WriteLine("total : " + total); Console.WriteLine("before message: " + routine.Notification.user.before.message); } JToken userDuring = userNotification["during"]; JToken userDuringMap = userDuring["mapValue"]["fields"]; routine.Notification.user.during.is_set = (bool)userDuringMap["is_set"]["booleanValue"] && (userDuringMap["date_set"] != null) ? IsDateToday(userDuringMap["date_set"]["stringValue"].ToString()) : false; routine.Notification.user.during.is_enabled = (bool)userDuringMap["is_enabled"]["booleanValue"]; if (routine.Notification.user.during.is_enabled && !routine.Notification.user.during.is_set) { routine.Notification.user.during.time = TimeSpan.Parse(userDuringMap["time"]["stringValue"].ToString()); //TotalMinutes double total = routine.Notification.user.during.time.TotalSeconds + (routine.availableStartTime - DateTime.Now.TimeOfDay).TotalSeconds; routine.Notification.user.during.message = userDuringMap["message"]["stringValue"].ToString(); if (!routine.isComplete && total > 0 && !routine.Notification.user.during.is_set) { string title = "Time for " + routine.title; string subtitle = routineIdx + routine.id; string message = "Open the app to review your tasks. " + routine.Notification.user.during.message; notificationManager.ScheduleNotification(title, subtitle, message, total); firebaseFunctionsService.GRUserNotificationSetToTrue(routine.id, routine.dbIdx.ToString(), "during"); } Console.WriteLine("total : " + total); Console.WriteLine("during message: " + routine.Notification.user.during.message); } JToken userAfter = userNotification["after"]; JToken userAfterMap = userAfter["mapValue"]["fields"]; Console.WriteLine("userAfterMap" + userAfterMap); // is_set to make sure notification is not already stored on phone routine.Notification.user.after.is_set = (bool)userAfterMap["is_set"]["booleanValue"] && (userAfterMap["date_set"] != null) ? IsDateToday(userAfterMap["date_set"]["stringValue"].ToString()) : false; routine.Notification.user.after.is_enabled = (bool)userAfterMap["is_enabled"]["booleanValue"]; if (routine.Notification.user.after.is_enabled && !routine.Notification.user.after.is_set) { routine.Notification.user.after.time = TimeSpan.Parse(userAfterMap["time"]["stringValue"].ToString()); //TotalMinutes double total = routine.Notification.user.after.time.TotalSeconds + (routine.availableEndTime - DateTime.Now.TimeOfDay).TotalSeconds; routine.Notification.user.after.message = userAfterMap["message"]["stringValue"].ToString(); if (!routine.isComplete && total > 0 && !routine.Notification.user.after.is_set) { string title = "You missed " + routine.title; string subtitle = routineIdx + routine.id; string message = "Open the app to review your tasks. " + routine.Notification.user.after.message; notificationManager.ScheduleNotification(title, subtitle, message, total); firebaseFunctionsService.GRUserNotificationSetToTrue(routine.id, routine.dbIdx.ToString(), "after"); } Console.WriteLine("total : " + total); Console.WriteLine("after message: " + routine.Notification.user.after.message); } } catch (Exception e) { Console.WriteLine("NOTIFICATION ERROR"); Console.WriteLine("{0} Exception caught.", e); } notificationManager.PrintPendingNotifications(); App.User.routines.Add(routine); routineIdx++; //Console.WriteLine("on Routine: " + routine.title + " " + routine.id); } else { goal goal = new goal { title = jsonMapGorR["title"]["stringValue"].ToString(), id = jsonMapGorR["id"]["stringValue"].ToString(), photo = jsonMapGorR["photo"]["stringValue"].ToString(), isInProgress = isInProgressCheck && IsDateToday(jsonMapGorR["datetime_started"]["stringValue"].ToString()), isComplete = (bool)jsonMapGorR["is_complete"]["booleanValue"] && IsDateToday(jsonMapGorR["datetime_completed"]["stringValue"].ToString()) && !isInProgressCheck, dbIdx = dbIdx_, isSublistAvailable = (bool)jsonMapGorR["is_sublist_available"]["booleanValue"], expectedCompletionTime = TimeSpan.Parse(jsonMapGorR["expected_completion_time"]["stringValue"].ToString()), dateTimeCompleted = DateTime.Parse(jsonMapGorR["datetime_completed"]["stringValue"].ToString()).ToLocalTime(), availableStartTime = TimeSpan.Parse(jsonMapGorR["available_start_time"]["stringValue"].ToString()), availableEndTime = TimeSpan.Parse(jsonMapGorR["available_end_time"]["stringValue"].ToString()) }; App.User.goals.Add(goal); goalIdx++; ////Console.WriteLine("on Goal: " + goal.id); } } } catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); } dbIdx_++; } App.User.routines.Sort((x, y) => TimeSpan.Compare(x.availableStartTime, y.availableStartTime)); App.User.goals.Sort((x, y) => TimeSpan.Compare(x.availableStartTime, y.availableStartTime)); routineIdx = 0; foreach (routine routine in App.User.routines) { LoadTasks(routine.id, routineIdx, "routine"); routineIdx++; } goalIdx = 0; foreach (goal goal in App.User.goals) { LoadTasks(goal.id, goalIdx, "goal"); goalIdx++; } } }