1 /**
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  *      http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 package com.android.healthconnect.controller.entrydetails
15 
16 import android.util.Log
17 import androidx.lifecycle.LiveData
18 import androidx.lifecycle.MutableLiveData
19 import androidx.lifecycle.ViewModel
20 import androidx.lifecycle.viewModelScope
21 import com.android.healthconnect.controller.data.entries.FormattedEntry
22 import com.android.healthconnect.controller.permissions.data.HealthPermissionType
23 import com.android.healthconnect.controller.shared.usecase.UseCaseResults
24 import dagger.hilt.android.lifecycle.HiltViewModel
25 import javax.inject.Inject
26 import kotlinx.coroutines.launch
27 
28 @HiltViewModel
29 class DataEntryDetailsViewModel
30 @Inject
31 constructor(private val loadEntryDetailsUseCase: LoadEntryDetailsUseCase) : ViewModel() {
32 
33     companion object {
34         private const val TAG = "DataEntryDetailsVM"
35     }
36 
37     private val _sessionData = MutableLiveData<DateEntryFragmentState>()
38     val sessionData: LiveData<DateEntryFragmentState>
39         get() = _sessionData
40 
loadEntryDatanull41     fun loadEntryData(
42         permissionType: HealthPermissionType,
43         entryId: String,
44         showDataOrigin: Boolean
45     ) {
46         viewModelScope.launch {
47             val response =
48                 loadEntryDetailsUseCase.invoke(
49                     LoadDataEntryInput(permissionType, entryId, showDataOrigin))
50             when (response) {
51                 is UseCaseResults.Success -> {
52                     _sessionData.postValue(DateEntryFragmentState.WithData(response.data))
53                 }
54                 is UseCaseResults.Failed -> {
55                     _sessionData.postValue(DateEntryFragmentState.LoadingFailed)
56                     Log.e(TAG, "Failed to Load Entry!", response.exception)
57                 }
58             }
59         }
60     }
61 
62     sealed class DateEntryFragmentState {
63         object Loading : DateEntryFragmentState()
64 
65         object LoadingFailed : DateEntryFragmentState()
66 
67         data class WithData(val data: List<FormattedEntry>) : DateEntryFragmentState()
68     }
69 }
70