1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.healthconnect.testapps.toolbox.viewmodels
18 
19 import android.content.Context
20 import android.health.connect.HealthConnectManager
21 import android.health.connect.ReadRecordsRequestUsingFilters
22 import android.health.connect.TimeInstantRangeFilter
23 import android.health.connect.datatypes.ExerciseSessionRecord
24 import androidx.lifecycle.LiveData
25 import androidx.lifecycle.MutableLiveData
26 import androidx.lifecycle.ViewModel
27 import androidx.lifecycle.viewModelScope
28 import com.android.healthconnect.testapps.toolbox.utils.GeneralUtils.Companion.readRecords
29 import java.time.Instant
30 import kotlinx.coroutines.launch
31 
32 class RouteRequestViewModel : ViewModel() {
33 
34     private val _exerciseSessionRecords = MutableLiveData<Result<List<ExerciseSessionRecord>>>()
35     val exerciseSessionRecords: LiveData<Result<List<ExerciseSessionRecord>>>
36         get() = _exerciseSessionRecords
37 
readExerciseSessionRecordsnull38     fun readExerciseSessionRecords(context: Context) {
39         val healthConnectManager = context.getSystemService(HealthConnectManager::class.java)!!
40 
41         val request =
42             ReadRecordsRequestUsingFilters.Builder(ExerciseSessionRecord::class.java)
43                 .setTimeRangeFilter(
44                     TimeInstantRangeFilter.Builder().setEndTime(Instant.now()).build())
45                 .setAscending(false)
46                 .setPageSize(10)
47                 .build()
48 
49         viewModelScope.launch {
50             try {
51                 val response = readRecords(healthConnectManager, request)
52                 _exerciseSessionRecords.postValue(Result.success(response))
53             } catch (e: Exception) {
54                 _exerciseSessionRecords.postValue(Result.failure(e))
55             }
56         }
57     }
58 }
59