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 package com.android.settings.datausage.lib
18
19 import android.content.Context
20 import android.text.format.DateUtils
21 import android.util.Range
22 import com.android.settings.R
23 import com.android.settings.datausage.lib.DataUsageFormatter.FormattedDataUsage
24
25 /**
26 * Base data structure representing usage data in a period.
27 */
28 data class NetworkUsageData(
29 val startTime: Long,
30 val endTime: Long,
31 val usage: Long,
32 ) {
33 val timeRange = Range(startTime, endTime)
34
formatStartDatenull35 fun formatStartDate(context: Context): String =
36 DateUtils.formatDateTime(context, startTime, DATE_FORMAT)
37
38 fun formatDateRange(context: Context): String =
39 DateUtils.formatDateRange(context, startTime, endTime, DATE_FORMAT)
40
41 fun formatUsage(context: Context): FormattedDataUsage =
42 DataUsageFormatter(context).formatDataUsage(usage)
43
44 fun getDataUsedString(context: Context): FormattedDataUsage =
45 formatUsage(context).format(context, R.string.data_used_template)
46
47 companion object {
48 val AllZero = NetworkUsageData(
49 startTime = 0L,
50 endTime = 0L,
51 usage = 0L,
52 )
53
54 private const val DATE_FORMAT = DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_ABBREV_MONTH
55 }
56 }
57
Listnull58 fun List<NetworkUsageData>.aggregate(): NetworkUsageData? = when {
59 isEmpty() -> null
60 else -> NetworkUsageData(
61 startTime = minOf { it.startTime },
62 endTime = maxOf { it.endTime },
63 usage = sumOf { it.usage },
64 )
65 }
66