From 518a2fa420eef5a758e30bab6712c728b012036d Mon Sep 17 00:00:00 2001 From: rudrankbasant Date: Sun, 28 Jan 2024 19:41:01 +0530 Subject: [PATCH] feat: store and fetch timetable from cache --- .../dscvit/vitty/ui/schedule/DayFragment.kt | 172 ++++++----- .../dscvit/vitty/widget/NextClassWidget.kt | 200 +++++++++---- .../com/dscvit/vitty/widget/TodayWidget.kt | 278 ++++++++++++------ 3 files changed, 417 insertions(+), 233 deletions(-) diff --git a/app/src/main/java/com/dscvit/vitty/ui/schedule/DayFragment.kt b/app/src/main/java/com/dscvit/vitty/ui/schedule/DayFragment.kt index 2972321..beee4b1 100755 --- a/app/src/main/java/com/dscvit/vitty/ui/schedule/DayFragment.kt +++ b/app/src/main/java/com/dscvit/vitty/ui/schedule/DayFragment.kt @@ -1,25 +1,22 @@ package com.dscvit.vitty.ui.schedule import android.content.Context -import android.content.Intent import android.content.SharedPreferences -import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast -import androidx.core.view.ViewCompat.setNestedScrollingEnabled import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.dscvit.vitty.R -import com.dscvit.vitty.activity.InstructionsActivity import com.dscvit.vitty.adapter.PeriodAdapter import com.dscvit.vitty.databinding.FragmentDayBinding import com.dscvit.vitty.model.PeriodDetails import com.dscvit.vitty.network.api.community.responses.timetable.Course +import com.dscvit.vitty.network.api.community.responses.user.UserResponse import com.dscvit.vitty.util.Constants import com.dscvit.vitty.util.Constants.DEFAULT_QUOTE import com.dscvit.vitty.util.Constants.USER_INFO @@ -27,7 +24,7 @@ import com.dscvit.vitty.util.Quote import com.dscvit.vitty.util.UtilFunctions import com.google.firebase.Timestamp import com.google.firebase.firestore.FirebaseFirestore -import com.google.firebase.firestore.Source +import com.google.gson.Gson import timber.log.Timber import java.text.SimpleDateFormat import java.util.Date @@ -40,7 +37,8 @@ class DayFragment : Fragment() { private var fragID = -1 private lateinit var sharedPref: SharedPreferences private val db = FirebaseFirestore.getInstance() - private val days = listOf("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday") + private val days = + listOf("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday") lateinit var day: String private lateinit var scheduleViewModel: ScheduleViewModel @@ -61,9 +59,19 @@ class DayFragment : Fragment() { //get token and username from shared preferences val sharedPreferences = activity?.getSharedPreferences(USER_INFO, Context.MODE_PRIVATE) val token = sharedPreferences?.getString(Constants.COMMUNITY_TOKEN, "") ?: "" - val username = requireArguments().getString("username") ?: sharedPreferences?.getString(Constants.COMMUNITY_USERNAME, null) ?: "" + val username = requireArguments().getString("username") ?: sharedPreferences?.getString( + Constants.COMMUNITY_USERNAME, + null + ) ?: "" Timber.d("token $token username $username") - Timber.d("pref username is ${sharedPreferences?.getString(Constants.COMMUNITY_USERNAME, null)}") + Timber.d( + "pref username is ${ + sharedPreferences?.getString( + Constants.COMMUNITY_USERNAME, + null + ) + }" + ) scheduleViewModel.getUserWithTimeTable(token, username) fragID = requireArguments().getString("frag_id")?.toInt()!! getData() @@ -81,81 +89,90 @@ class DayFragment : Fragment() { "saturday" ).toString() else days[fragID] - scheduleViewModel.user.observe(viewLifecycleOwner){ - if(it!=null){ + val cachedData = sharedPref.getString(Constants.CACHE_COMMUNITY_TIMETABLE, null) + if (cachedData != null) { + // If cached data is available, load from cache + Timber.d("Loading from cache") + Timber.d("$cachedData") + val response = Gson().fromJson(cachedData, UserResponse::class.java) +// Toast.makeText(context, "Loaded from cache", Toast.LENGTH_SHORT).show() + processTimetableData(response) + UtilFunctions.reloadWidgets(requireContext()) + } + + + scheduleViewModel.user.observe(viewLifecycleOwner) { + if (it != null) { + //cache response for widget + val response = Gson().toJson(it) + val editor = sharedPref.edit() + editor.putString(Constants.CACHE_COMMUNITY_TIMETABLE, response) + editor.apply() + val cachedData = sharedPref.getString(Constants.CACHE_COMMUNITY_TIMETABLE, null) + Timber.d("cached data is $cachedData") +// Toast.makeText(context, "Updated Timetable from internet.", Toast.LENGTH_SHORT).show() + + Timber.d(it.toString()) - val timetableDays = it.timetable?.data - when(day){ - "monday" -> { - val monday = timetableDays?.Monday - setUpDayTimeTable(monday) - } - "tuesday" -> { - val tuesday = timetableDays?.Tuesday - setUpDayTimeTable(tuesday) - } - "wednesday" -> { - val wednesday = timetableDays?.Wednesday - setUpDayTimeTable(wednesday) - } - "thursday" -> { - val thursday = timetableDays?.Thursday - setUpDayTimeTable(thursday) - } - "friday" -> { - val friday = timetableDays?.Friday - setUpDayTimeTable(friday) - } - "saturday" -> { - val saturday = timetableDays?.Saturday - setUpDayTimeTable(saturday) - } - "sunday" -> { - val sunday = timetableDays?.Sunday - setUpDayTimeTable(sunday) - } - } + processTimetableData(it) - }else{ - Toast.makeText(context, "Error fetching timetable", Toast.LENGTH_SHORT).show() + } else { + if (cachedData == null) { + Toast.makeText(context, "Error fetching timetable", Toast.LENGTH_SHORT).show() + + } binding.loadingView.visibility = View.GONE } } - /*if (uid != null) { - db.collection("users") - .document(uid) - .collection("timetable") - .document(day) - .collection("periods") - .get(Source.CACHE) - .addOnSuccessListener { result -> - for (document in result) { - try { - val pd = PeriodDetails( - document.getString("courseCode")!!, - document.getString("courseName")!!, - document.getTimestamp("startTime")!!, - document.getTimestamp("endTime")!!, - document.getString("slot")!!, - document.getString("location")!! - ) - courseList.add(pd) - } catch (e: Exception) { - } - } - scheduleSetup() - } - .addOnFailureListener { e -> - Timber.d("Auth error: $e") - } - }*/ + + } + + private fun processTimetableData(userResponse: UserResponse) { + val timetableDays = userResponse.timetable?.data + when (day) { + "monday" -> { + val monday = timetableDays?.Monday + setUpDayTimeTable(monday) + } + + "tuesday" -> { + val tuesday = timetableDays?.Tuesday + setUpDayTimeTable(tuesday) + } + + "wednesday" -> { + val wednesday = timetableDays?.Wednesday + setUpDayTimeTable(wednesday) + } + + "thursday" -> { + val thursday = timetableDays?.Thursday + setUpDayTimeTable(thursday) + } + + "friday" -> { + val friday = timetableDays?.Friday + setUpDayTimeTable(friday) + } + + "saturday" -> { + val saturday = timetableDays?.Saturday + setUpDayTimeTable(saturday) + } + + "sunday" -> { + val sunday = timetableDays?.Sunday + setUpDayTimeTable(sunday) + } + + } } private fun setUpDayTimeTable(day: List?) { courseList.clear() - if(!day.isNullOrEmpty()){ - for (course in day){ + if (!day.isNullOrEmpty()) { + for (course in day) { val pd = PeriodDetails( course.code, course.name, @@ -175,7 +192,7 @@ class DayFragment : Fragment() { private fun parseTimeToTimestamp(timeString: String): Timestamp { - try{ + try { val time = replaceYearIfZero(timeString) val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") // Set the time zone of the date format to UTC @@ -186,10 +203,10 @@ class DayFragment : Fragment() { val localTimeZone = TimeZone.getDefault() val localDate = Date(date.time) return Timestamp(localDate) - }else{ + } else { return Timestamp.now() } - }catch (e: Exception) { + } catch (e: Exception) { Timber.d("Date----: ${e.message}") return Timestamp.now() } @@ -204,6 +221,7 @@ class DayFragment : Fragment() { return dateStr } } + private fun scheduleSetup() { binding.apply { if (courseList.isNotEmpty()) { @@ -231,7 +249,7 @@ class DayFragment : Fragment() { "saturday" ).toString() ) { - getData() + getData() } } } diff --git a/app/src/main/java/com/dscvit/vitty/widget/NextClassWidget.kt b/app/src/main/java/com/dscvit/vitty/widget/NextClassWidget.kt index db86679..b341450 100755 --- a/app/src/main/java/com/dscvit/vitty/widget/NextClassWidget.kt +++ b/app/src/main/java/com/dscvit/vitty/widget/NextClassWidget.kt @@ -21,7 +21,7 @@ import com.dscvit.vitty.util.Quote import com.dscvit.vitty.util.RemoteConfigUtils import com.dscvit.vitty.util.UtilFunctions import com.google.firebase.firestore.FirebaseFirestore -import com.google.firebase.firestore.Source +import com.google.gson.Gson import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.runBlocking import retrofit2.Call @@ -75,6 +75,15 @@ internal fun updateNextClassWidget( ) views.setOnClickPendingIntent(R.id.next_class_widget, pendingIntent) + + // Add the following lines to update the text with the current date and time + val currentDate = SimpleDateFormat("MMM dd, yyyy", Locale.getDefault()).format(Date()) + val currentTime = SimpleDateFormat("hh:mm a", Locale.getDefault()).format(Date()) + val currentDateTime = "$currentDate $currentTime" + + // Assuming "refresh_text" is the ID of the TextView you want to update +// views.setTextViewText(R.id.refresh_widget, currentDateTime) + val sharedPref = context.getSharedPreferences("login_info", Context.MODE_PRIVATE)!! if (sharedPref.getBoolean(Constants.EXAM_MODE, false)) { views.setTextViewText( @@ -199,46 +208,161 @@ suspend fun fetchData( .toString() else oldDay val uid = sharedPref.getString("uid", "") var pd = PeriodDetails() - val sharedPreferences = context.getSharedPreferences(Constants.USER_INFO, Context.MODE_PRIVATE) + val sharedPreferences = + context.getSharedPreferences(Constants.USER_INFO, Context.MODE_PRIVATE) val token = sharedPreferences?.getString(Constants.COMMUNITY_TOKEN, "") ?: "" - val username = sharedPreferences?.getString(Constants.COMMUNITY_USERNAME, null) ?: "" + val username = sharedPreferences?.getString(Constants.COMMUNITY_USERNAME, null) ?: "" + val cachedData = sharedPref.getString(Constants.CACHE_COMMUNITY_TIMETABLE, null) + if (cachedData != null) { + // If cached data is available, load from cache + Timber.d("Loading from cache") + Timber.d("$cachedData") + val response = Gson().fromJson(cachedData, UserResponse::class.java) + + val user = response + if (user?.timetable?.data == null) { + pd.courseName = "" + updateNextClassWidget(context, appWidgetManager, appWidgetId, pd) + return@coroutineScope + } + var today = user.timetable?.data?.Monday + + when (day) { + "monday" -> { + today = user.timetable?.data?.Monday + } + + "tuesday" -> { + today = user.timetable?.data?.Tuesday + } + + "wednesday" -> { + today = user.timetable?.data?.Wednesday + } + + "thursday" -> { + today = user.timetable?.data?.Thursday + } + + "friday" -> { + today = user.timetable?.data?.Friday + } + + "saturday" -> { + today = user.timetable?.data?.Saturday + } + + "sunday" -> { + today = user.timetable?.data?.Sunday + } + } + today = today?.sortedBy { it.start_time } +// if(today.isNullOrEmpty()){ +// pd.courseName = "" +// updateNextClassWidget(context, appWidgetManager, appWidgetId, pd) +// return@coroutineScope +// } + if (today != null) { + for (period in today) { + + try { + val start = Calendar.getInstance() + val s = Calendar.getInstance() + s.time = parseTimeToTimestamp(period.start_time).toDate() + start[Calendar.HOUR_OF_DAY] = s[Calendar.HOUR_OF_DAY] + start[Calendar.MINUTE] = s[Calendar.MINUTE] + Timber.d("$calendar") + Timber.d("$start") + if (start.time > calendar.time) { + val end = Calendar.getInstance() + val e = Calendar.getInstance() + e.time = parseTimeToTimestamp(period.end_time).toDate() + end[Calendar.HOUR_OF_DAY] = e[Calendar.HOUR_OF_DAY] + end[Calendar.MINUTE] = e[Calendar.MINUTE] + Timber.d("$end") + if (end.time > calendar.time) { + pd = PeriodDetails( + period.code, + period.name, + parseTimeToTimestamp(period.start_time), + parseTimeToTimestamp(period.end_time), + period.slot, + period.venue + ) + break + } + } else { + pd.courseName = "" + val simpleDateFormat = + SimpleDateFormat("h:mm a", Locale.getDefault()) + val sTime: String = + simpleDateFormat.format(calendar.time).uppercase(Locale.ROOT) + Timber.d("LOL: $sTime") + } + } catch (e: Exception) { + pd.courseName = "" + Timber.d("F: $e") + } + + + } + } + updateNextClassWidget(context, appWidgetManager, appWidgetId, pd) + + } + + + + if (cachedData == null) { APICommunityRestClient.instance.getUserWithTimeTable(token, username, object : RetrofitSelfUserListener { override fun onSuccess(call: Call?, response: UserResponse?) { val user = response - if(user?.timetable?.data == null){ + //cache response for widget + val jsonResponse = Gson().toJson(response) + val editor = sharedPref.edit() + editor.putString(Constants.CACHE_COMMUNITY_TIMETABLE, jsonResponse) + editor.apply() + + if (user?.timetable?.data == null) { pd.courseName = "" updateNextClassWidget(context, appWidgetManager, appWidgetId, pd) return } var today = user.timetable?.data?.Monday - when(day){ + when (day) { "monday" -> { today = user.timetable?.data?.Monday } + "tuesday" -> { today = user.timetable?.data?.Tuesday } + "wednesday" -> { today = user.timetable?.data?.Wednesday } + "thursday" -> { today = user.timetable?.data?.Thursday } + "friday" -> { today = user?.timetable?.data?.Friday } + "saturday" -> { today = user?.timetable?.data?.Saturday } + "sunday" -> { today = user?.timetable?.data?.Sunday } } today = today?.sortedBy { it.start_time } - for(period in today!!){ + for (period in today!!) { try { val start = Calendar.getInstance() @@ -251,7 +375,7 @@ suspend fun fetchData( if (start.time > calendar.time) { val end = Calendar.getInstance() val e = Calendar.getInstance() - e.time = parseTimeToTimestamp(period.end_time).toDate() + e.time = parseTimeToTimestamp(period.end_time).toDate() end[Calendar.HOUR_OF_DAY] = e[Calendar.HOUR_OF_DAY] end[Calendar.MINUTE] = e[Calendar.MINUTE] Timber.d("$end") @@ -271,7 +395,8 @@ suspend fun fetchData( val simpleDateFormat = SimpleDateFormat("h:mm a", Locale.getDefault()) val sTime: String = - simpleDateFormat.format(calendar.time).uppercase(Locale.ROOT) + simpleDateFormat.format(calendar.time) + .uppercase(Locale.ROOT) Timber.d("LOL: $sTime") } } catch (e: Exception) { @@ -290,62 +415,7 @@ suspend fun fetchData( updateNextClassWidget(context, appWidgetManager, appWidgetId, pd) } }) + } + -// if (uid != null && uid != "") { -// db.collection("users") -// .document(uid) -// .collection("timetable") -// .document(day) -// .collection("periods") -// .get(Source.CACHE) -// .addOnSuccessListener { result -> -// for (document in result) { -// try { -// val start = Calendar.getInstance() -// val s = Calendar.getInstance() -// s.time = document.getTimestamp("startTime")!!.toDate() -// start[Calendar.HOUR_OF_DAY] = s[Calendar.HOUR_OF_DAY] -// start[Calendar.MINUTE] = s[Calendar.MINUTE] -// Timber.d("$calendar") -// Timber.d("$start") -// if (start.time > calendar.time) { -// val end = Calendar.getInstance() -// val e = Calendar.getInstance() -// e.time = document.getTimestamp("endTime")!!.toDate() -// end[Calendar.HOUR_OF_DAY] = e[Calendar.HOUR_OF_DAY] -// end[Calendar.MINUTE] = e[Calendar.MINUTE] -// Timber.d("$end") -// if (end.time > calendar.time) { -// pd = PeriodDetails( -// document.getString("courseCode")!!, -// document.getString("courseName")!!, -// document.getTimestamp("startTime")!!, -// document.getTimestamp("endTime")!!, -// document.getString("slot")!!, -// document.getString("location")!! -// ) -// break -// } -// } else { -// pd.courseName = "" -// val simpleDateFormat = -// SimpleDateFormat("h:mm a", Locale.getDefault()) -// val sTime: String = -// simpleDateFormat.format(calendar.time).uppercase(Locale.ROOT) -// Timber.d("LOL: $sTime") -// } -// } catch (e: Exception) { -// pd.courseName = "" -// Timber.d("F: $e") -// } -// } -// updateNextClassWidget(context, appWidgetManager, appWidgetId, pd) -// } -// .addOnFailureListener { e -> -// Timber.d("Error: $e") -// } -// } else { -// pd.courseName = "" -// updateNextClassWidget(context, appWidgetManager, appWidgetId, pd) -// } } diff --git a/app/src/main/java/com/dscvit/vitty/widget/TodayWidget.kt b/app/src/main/java/com/dscvit/vitty/widget/TodayWidget.kt index f7a9cee..ade472e 100755 --- a/app/src/main/java/com/dscvit/vitty/widget/TodayWidget.kt +++ b/app/src/main/java/com/dscvit/vitty/widget/TodayWidget.kt @@ -7,14 +7,12 @@ import android.content.Context import android.content.Intent import android.os.Bundle import android.widget.RemoteViews -import androidx.lifecycle.ViewModelProvider import com.dscvit.vitty.R import com.dscvit.vitty.activity.AuthActivity import com.dscvit.vitty.network.api.community.APICommunityRestClient import com.dscvit.vitty.network.api.community.RetrofitSelfUserListener import com.dscvit.vitty.network.api.community.responses.user.UserResponse import com.dscvit.vitty.service.TodayWidgetService -import com.dscvit.vitty.ui.schedule.ScheduleViewModel import com.dscvit.vitty.util.ArraySaverLoader.saveArray import com.dscvit.vitty.util.Constants import com.dscvit.vitty.util.Constants.PERIODS @@ -23,7 +21,7 @@ import com.dscvit.vitty.util.Constants.TODAY_INTENT import com.dscvit.vitty.util.UtilFunctions import com.google.firebase.Timestamp import com.google.firebase.firestore.FirebaseFirestore -import com.google.firebase.firestore.Source +import com.google.gson.Gson import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.runBlocking import retrofit2.Call @@ -70,6 +68,8 @@ internal fun updateTodayWidget( ) { // Construct the RemoteViews object val views = RemoteViews(context.packageName, R.layout.today_widget) + + val intent = Intent(context, AuthActivity::class.java) val pendingIntent = PendingIntent.getActivity( context, @@ -78,6 +78,17 @@ internal fun updateTodayWidget( PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) views.setOnClickPendingIntent(R.id.today_widget, pendingIntent) + + + // Add the following lines to update the text with the current date and time + val currentDate = SimpleDateFormat("MMM dd, yyyy", Locale.getDefault()).format(Date()) + val currentTime = SimpleDateFormat("hh:mm a", Locale.getDefault()).format(Date()) + val currentDateTime = "$currentDate $currentTime" + + // Assuming "refesr_text" is the ID of the TextView you want to update +// views.setTextViewText(R.id.refresh_widget, currentDateTime) + + val days = listOf("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday") val calendar: Calendar = Calendar.getInstance() val d = when (calendar.get(Calendar.DAY_OF_WEEK)) { @@ -144,105 +155,190 @@ suspend fun fetchTodayData( val courseList: ArrayList = ArrayList() val timeList: ArrayList = ArrayList() val roomList: ArrayList = ArrayList() - val sharedPreferences = context.getSharedPreferences(Constants.USER_INFO, Context.MODE_PRIVATE) + val sharedPreferences = + context.getSharedPreferences(Constants.USER_INFO, Context.MODE_PRIVATE) val token = sharedPreferences?.getString(Constants.COMMUNITY_TOKEN, "") ?: "" - val username = sharedPreferences?.getString(Constants.COMMUNITY_USERNAME, null) ?: "" - APICommunityRestClient.instance.getUserWithTimeTable(token, username, - - object : RetrofitSelfUserListener { - override fun onSuccess(call: Call?, response: UserResponse?) { - val user = response - if(user?.timetable?.data == null){ - updateTodayWidget(context, appWidgetManager, appWidgetId, courseList, timeList, roomList) - return - } - var today = user.timetable?.data?.Monday + val username = sharedPreferences?.getString(Constants.COMMUNITY_USERNAME, null) ?: "" + val cachedData = sharedPref.getString(Constants.CACHE_COMMUNITY_TIMETABLE, null) + if (cachedData != null) { + // If cached data is available, load from cache + Timber.d("Loading from cache") + Timber.d("$cachedData") + val response = Gson().fromJson(cachedData, UserResponse::class.java) - when(day){ - "monday" -> { - today = user.timetable?.data?.Monday - } - "tuesday" -> { - today = user.timetable?.data?.Tuesday - } - "wednesday" -> { - today = user.timetable?.data?.Wednesday - } - "thursday" -> { - today = user.timetable?.data?.Thursday - } - "friday" -> { - today = user.timetable?.data?.Friday + val user = response + if (user?.timetable?.data == null) { + updateTodayWidget( + context, + appWidgetManager, + appWidgetId, + courseList, + timeList, + roomList + ) + return@coroutineScope + } + var today = user.timetable?.data?.Monday + + when (day) { + "monday" -> { + today = user.timetable?.data?.Monday + } + + "tuesday" -> { + today = user.timetable?.data?.Tuesday + } + + "wednesday" -> { + today = user.timetable?.data?.Wednesday + } + + "thursday" -> { + today = user.timetable?.data?.Thursday + } + + "friday" -> { + today = user.timetable?.data?.Friday + } + + "saturday" -> { + today = user.timetable?.data?.Saturday + } + + "sunday" -> { + today = user.timetable?.data?.Sunday + } + } + Timber.d("Today: ${user.timetable}") + today = today?.sortedBy { it.start_time } + if (today != null) { + for (period in today) { + var startTime = parseTimeToTimestamp(period.start_time).toDate() + var endTime = parseTimeToTimestamp(period.end_time).toDate() + + val simpleDateFormat = SimpleDateFormat("h:mm a", Locale.getDefault()) + val sTime: String = simpleDateFormat.format(startTime).uppercase(Locale.ROOT) + val eTime: String = simpleDateFormat.format(endTime).uppercase(Locale.ROOT) + courseList.add(period.name) + timeList.add("$sTime - $eTime") + roomList.add(period.venue) + } + } + + updateTodayWidget( + context, + appWidgetManager, + appWidgetId, + courseList, + timeList, + roomList + ) + } + + + if (cachedData == null) { + APICommunityRestClient.instance.getUserWithTimeTable(token, username, + + object : RetrofitSelfUserListener { + override fun onSuccess(call: Call?, response: UserResponse?) { + val user = response + + //cache response for widget + val jsonResponse = Gson().toJson(response) + val editor = sharedPref.edit() + editor.putString(Constants.CACHE_COMMUNITY_TIMETABLE, jsonResponse) + editor.apply() + + if (user?.timetable?.data == null) { + updateTodayWidget( + context, + appWidgetManager, + appWidgetId, + courseList, + timeList, + roomList + ) + return } - "saturday" -> { - today = user.timetable?.data?.Saturday + var today = user.timetable?.data?.Monday + + when (day) { + "monday" -> { + today = user.timetable?.data?.Monday + } + + "tuesday" -> { + today = user.timetable?.data?.Tuesday + } + + "wednesday" -> { + today = user.timetable?.data?.Wednesday + } + + "thursday" -> { + today = user.timetable?.data?.Thursday + } + + "friday" -> { + today = user.timetable?.data?.Friday + } + + "saturday" -> { + today = user.timetable?.data?.Saturday + } + + "sunday" -> { + today = user.timetable?.data?.Sunday + } } - "sunday" -> { - today = user.timetable?.data?.Sunday + today = today?.sortedBy { it.start_time } + for (period in today!!) { + var startTime = parseTimeToTimestamp(period.start_time).toDate() + var endTime = parseTimeToTimestamp(period.end_time).toDate() + + val simpleDateFormat = SimpleDateFormat("h:mm a", Locale.getDefault()) + val sTime: String = + simpleDateFormat.format(startTime).uppercase(Locale.ROOT) + val eTime: String = + simpleDateFormat.format(endTime).uppercase(Locale.ROOT) + courseList.add(period.name) + timeList.add("$sTime - $eTime") + roomList.add(period.venue) } - } - today = today?.sortedBy { it.start_time } - for(period in today!!){ - var startTime = parseTimeToTimestamp(period.start_time).toDate() - var endTime = parseTimeToTimestamp(period.end_time).toDate() - - val simpleDateFormat = SimpleDateFormat("h:mm a", Locale.getDefault()) - val sTime: String = simpleDateFormat.format(startTime).uppercase(Locale.ROOT) - val eTime: String = simpleDateFormat.format(endTime).uppercase(Locale.ROOT) - courseList.add(period.name) - timeList.add("$sTime - $eTime") - roomList.add(period.venue) - } - updateTodayWidget(context, appWidgetManager, appWidgetId, courseList, timeList, roomList) + updateTodayWidget( + context, + appWidgetManager, + appWidgetId, + courseList, + timeList, + roomList + ) - } + } + + override fun onError(call: Call?, t: Throwable?) { + Timber.d("Error YO: $t") + updateTodayWidget( + context, + appWidgetManager, + appWidgetId, + courseList, + timeList, + roomList + ) + + } + }) + } - override fun onError(call: Call?, t: Throwable?) { - Timber.d("Error YO: $t") - updateTodayWidget(context, appWidgetManager, appWidgetId, courseList, timeList, roomList) - } - }) -// if (uid != null && uid != "") { -// db.collection("users") -// .document(uid) -// .collection("timetable") -// .document(day) -// .collection("periods") -// .get(Source.CACHE) -// .addOnSuccessListener { result -> -// for (document in result) { -// try { -// val startTime: Date = document.getTimestamp("startTime")!!.toDate() -// val simpleDateFormat = SimpleDateFormat("h:mm a", Locale.getDefault()) -// val sTime: String = -// simpleDateFormat.format(startTime).uppercase() -// -// val endTime: Date = document.getTimestamp("endTime")!!.toDate() -// val eTime: String = -// simpleDateFormat.format(endTime).uppercase() -// -// courseList.add(document.getString("courseName")!!) -// timeList.add("$sTime - $eTime") -// roomList.add(document.getString("location")!!) -// } catch (e: Exception) { -// Timber.d("Error: $e") -// } -// } -// updateTodayWidget(context, appWidgetManager, appWidgetId, courseList, timeList, roomList) -// } -// .addOnFailureListener { e -> -// Timber.d("Error YO: $e") -// } -// } else { -// updateTodayWidget(context, appWidgetManager, appWidgetId, courseList, timeList, roomList) -// } } + fun parseTimeToTimestamp(timeString: String): Timestamp { - try{ + try { val time = replaceYearIfZero(timeString) val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") // Set the time zone of the date format to UTC @@ -253,10 +349,10 @@ fun parseTimeToTimestamp(timeString: String): Timestamp { val localTimeZone = TimeZone.getDefault() val localDate = Date(date.time) return Timestamp(localDate) - }else{ + } else { return Timestamp.now() } - }catch (e: Exception) { + } catch (e: Exception) { Timber.d("Date----: ${e.message}") return Timestamp.now() }