1 /**
2  * Copyright (C) 2022 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  * ```
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * ```
10  *
11  * Unless required by applicable law or agreed to in writing, software distributed under the License
12  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13  * or implied. See the License for the specific language governing permissions and limitations under
14  * the License.
15  */
16 package com.android.healthconnect.controller.dataentries.formatters
17 
18 import android.content.Context
19 import android.health.connect.datatypes.units.Energy
20 import android.icu.text.MessageFormat.format
21 import androidx.annotation.StringRes
22 import com.android.healthconnect.controller.R
23 import com.android.healthconnect.controller.dataentries.units.EnergyConverter.convertToJoules
24 import com.android.healthconnect.controller.dataentries.units.EnergyUnit
25 import com.android.healthconnect.controller.dataentries.units.EnergyUnit.CALORIE
26 import com.android.healthconnect.controller.dataentries.units.EnergyUnit.KILOJOULE
27 import com.android.healthconnect.controller.dataentries.units.UnitPreferences
28 import kotlin.math.roundToInt
29 
30 /** Format energy strings (calories and kj) */
31 object EnergyFormatter {
formatEnergyValuenull32     fun formatEnergyValue(
33         context: Context,
34         energy: Energy,
35         unitPreferences: UnitPreferences
36     ): String {
37         val res =
38             when (unitPreferences.getEnergyUnit()) {
39                 CALORIE -> R.string.calories
40                 KILOJOULE -> R.string.kj
41             }
42         return formatEnergy(context, res, energy, unitPreferences.getEnergyUnit())
43     }
44 
formatEnergyA11yValuenull45     fun formatEnergyA11yValue(
46         context: Context,
47         energy: Energy,
48         unitPreferences: UnitPreferences
49     ): String {
50         val res =
51             when (unitPreferences.getEnergyUnit()) {
52                 CALORIE -> R.string.calories_long
53                 KILOJOULE -> R.string.kj_long
54             }
55         return formatEnergy(context, res, energy, unitPreferences.getEnergyUnit())
56     }
57 
formatEnergynull58     private fun formatEnergy(
59         context: Context,
60         @StringRes res: Int,
61         energy: Energy,
62         energyUnit: EnergyUnit
63     ): String {
64         val value =
65             when (energyUnit) {
66                 CALORIE -> energy.inCalories / 1000.0
67                 KILOJOULE -> convertToJoules(energy.inCalories) / 1000.0
68             }
69         return format(context.getString(res), mapOf("count" to value.roundToInt()))
70     }
71 }
72