1 /**
<lambda>null2  * 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.autodelete
17 
18 import com.android.healthconnect.controller.utils.TimeSource
19 import java.time.Instant
20 import java.time.LocalDateTime
21 
22 /**
23  * Specifies the range of auto-deletion, where data wil be automatically deleted from (no data gets
24  * deleted in case of [AutoDeleteRange.AUTO_DELETE_RANGE_NEVER]).
25  *
26  * @param numberOfMonths: number of months used to retention the data.
27  */
28 enum class AutoDeleteRange(val numberOfMonths: Int) {
29     AUTO_DELETE_RANGE_NEVER(0),
30     AUTO_DELETE_RANGE_THREE_MONTHS(3),
31     AUTO_DELETE_RANGE_EIGHTEEN_MONTHS(18)
32 }
33 
34 /**
35  * Returns [AutoDeleteRange] corresponding to the given number of months or throws in case of
36  * unsupported number of months.
37  */
fromNumberOfMonthsnull38 fun fromNumberOfMonths(numberOfMonths: Int): AutoDeleteRange {
39     AutoDeleteRange.values().forEach { range ->
40         if (range.numberOfMonths == numberOfMonths) {
41             return range
42         }
43     }
44     throw UnsupportedOperationException("Number of months is not supported: $numberOfMonths")
45 }
46 
47 /** Returns the [Instant] that is the start of the [AutoDeleteRange]. */
autoDeleteRangeStartnull48 fun autoDeleteRangeStart(): Instant {
49     return Instant.EPOCH
50 }
51 
52 /**
53  * Returns the [Instant] that is the end of the [AutoDeleteRange] or throws in case of
54  * [AutoDeleteRange.AUTO_DELETE_RANGE_NEVER].
55  */
autoDeleteRangeEndnull56 fun autoDeleteRangeEnd(timeSource: TimeSource, range: AutoDeleteRange): Instant {
57     val localDateTimeNow: LocalDateTime = timeSource.currentLocalDateTime()
58     when (range) {
59         AutoDeleteRange.AUTO_DELETE_RANGE_THREE_MONTHS,
60         AutoDeleteRange.AUTO_DELETE_RANGE_EIGHTEEN_MONTHS -> {
61             val exactlyXMonthsAgo: LocalDateTime =
62                 localDateTimeNow.minusMonths(range.numberOfMonths.toLong())
63             return exactlyXMonthsAgo
64                 .toLocalDate()
65                 .atStartOfDay(timeSource.deviceZoneOffset())
66                 .toInstant()
67         }
68         AutoDeleteRange.AUTO_DELETE_RANGE_NEVER -> {
69             throw UnsupportedOperationException("Invalid auto-delete range to delete data.")
70         }
71     }
72 }
73