1 /*
2  * Copyright (C) 2023 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  */
18 package com.android.healthconnect.controller.data.appdata
19 
20 import androidx.lifecycle.LiveData
21 import androidx.lifecycle.MutableLiveData
22 import androidx.lifecycle.ViewModel
23 import androidx.lifecycle.viewModelScope
24 import com.android.healthconnect.controller.shared.app.AppInfoReader
25 import com.android.healthconnect.controller.shared.app.AppMetadata
26 import com.android.healthconnect.controller.shared.usecase.UseCaseResults
27 import dagger.hilt.android.lifecycle.HiltViewModel
28 import javax.inject.Inject
29 import kotlinx.coroutines.launch
30 
31 /** View model for the [AppDataFragment] . */
32 @HiltViewModel
33 class AppDataViewModel
34 @Inject
35 constructor(
36     private val appInfoReader: AppInfoReader,
37     private val loadAppDataUseCase: AppDataUseCase
38 ) : ViewModel() {
39 
40     companion object {
41         private const val TAG = "AppDataViewModel"
42     }
43 
44     private val _appData = MutableLiveData<AppDataState>()
45     private val _appInfo = MutableLiveData<AppMetadata>()
46 
47     /** Provides a list of [PermissionTypesPerCategory]s to be displayed in [AppDataFragment]. */
48     val appData: LiveData<AppDataState>
49         get() = _appData
50 
51     val appInfo: LiveData<AppMetadata>
52         get() = _appInfo
53 
loadAppDatanull54     fun loadAppData(packageName: String) {
55         _appData.postValue(AppDataState.Loading)
56 
57         viewModelScope.launch {
58             when (val result = loadAppDataUseCase.loadAppData(packageName)) {
59                 is UseCaseResults.Success -> {
60                     _appData.postValue(AppDataState.WithData(result.data))
61                 }
62                 is UseCaseResults.Failed -> {
63                     _appData.postValue(AppDataState.Error)
64                 }
65             }
66         }
67     }
68 
loadAppInfonull69     fun loadAppInfo(packageName: String) {
70         viewModelScope.launch { _appInfo.postValue(appInfoReader.getAppMetadata(packageName)) }
71     }
72 
73     sealed class AppDataState {
74         object Loading : AppDataState()
75 
76         object Error : AppDataState()
77 
78         data class WithData(val dataMap: List<PermissionTypesPerCategory>) : AppDataState()
79     }
80 }
81