Release 4.0.0-preview1-00051
[platform/core/csapi/tizenfx.git] / src / Tizen.Context / Tizen.Context.AppHistory / BatteryStatistics.cs
1 /*
2  * Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
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 using System;
18 using System.Collections.Generic;
19
20 namespace Tizen.Context.AppHistory
21 {
22     /// <summary>
23     /// This class provides APIs to query battery consumption per application.
24     /// </summary>
25     public class BatteryStatistics : AppStatistics
26     {
27         private const string AppStatsConsumption = "TotalAmount";
28
29         /// <summary>
30         ///  The default constructor of BatteryStatistics class.
31         /// </summary>
32         /// <feature>http://tizen.org/feature/battery</feature>
33         /// <exception cref="InvalidOperationException">Thrown when method fail due to internal error.</exception>
34         /// <exception cref="NotSupportedException">Thrown when the statistics is not supported.</exception>
35         public BatteryStatistics()
36         {
37             SortOrder = SortOrderType.ConsumptionMost;
38             Uri = ConvertSortOrderToString((int)SortOrder);
39
40             bool isSupported = false;
41             int error = Interop.CtxHistory.IsSupported(Uri, out isSupported);
42             if ((AppHistoryError)error != AppHistoryError.None)
43             {
44                 throw AppHistoryErrorFactory.CheckAndThrowException((AppHistoryError)error, Uri);
45             }
46
47             if (!isSupported)
48             {
49                 throw AppHistoryErrorFactory.CheckAndThrowException(AppHistoryError.NotSupported, Uri);
50             }
51         }
52
53         /// <summary>
54         /// The constructor of BatteryStatistics class.
55         /// </summary>
56         /// <param name="order">The criteria of the battery statistics sorted by.</param>
57         /// <feature>http://tizen.org/feature/battery</feature>
58         /// <exception cref="ArgumentException">Thrown when an invalid argument is used.</exception>
59         /// <exception cref="InvalidOperationException">Thrown when method fail due to internal error.</exception>
60         /// <exception cref="NotSupportedException">Thrown when the statistics is not supported.</exception>
61         public BatteryStatistics(SortOrderType order)
62         {
63             SortOrder = order;
64             Uri = ConvertSortOrderToString((int)SortOrder);
65
66             if (Uri == null)
67             {
68                 throw AppHistoryErrorFactory.CheckAndThrowException(AppHistoryError.InvalidParameter, "Invalid SortOrderType");
69             }
70
71             bool isSupported = false;
72             int error = Interop.CtxHistory.IsSupported(Uri, out isSupported);
73             if ((AppHistoryError)error != AppHistoryError.None)
74             {
75                 throw AppHistoryErrorFactory.CheckAndThrowException((AppHistoryError)error, Uri);
76             }
77
78             if (!isSupported)
79             {
80                 throw AppHistoryErrorFactory.CheckAndThrowException(AppHistoryError.NotSupported, Uri);
81             }
82         }
83
84         /// <summary>
85         /// Retrieves a given type of battery statistics.
86         /// </summary>
87         /// <param name="startTime">The start time of the data to be aggregated.</param>
88         /// <param name="endTime">The end time of the data to be aggregated.</param>
89         /// <returns>Battery statistics data retrieved.</returns>
90         /// <privilege>http://tizen.org/privilege/apphistory.read</privilege>
91         /// <exception cref="ArgumentException">Thrown when an invalid argument is used.</exception>
92         /// <exception cref="InvalidOperationException">Thrown when invalid operation occurs.</exception>
93         /// <exception cref="UnauthorizedAccessException">Thrown when the app has no privilege to retrieve app history.</exception>
94         public IReadOnlyList<BatteryStatisticsData> Query(DateTime startTime, DateTime endTime)
95         {
96             CheckTimeSpan(startTime, endTime);
97
98             return Query(startTime, endTime, DefaultResultSize);
99         }
100
101         /// <summary>
102         /// Retrieves a given type of battery statistics.
103         /// </summary>
104         /// <param name="startTime">The start time of the data to be aggregated.</param>
105         /// <param name="endTime">The end time of the data to be aggregated.</param>
106         /// <param name="resultSize">The number of data records to be retrieved.</param>
107         /// <returns>Battery statistics data retrieved.</returns>
108         /// <privilege>http://tizen.org/privilege/apphistory.read</privilege>
109         /// <exception cref="ArgumentException">Thrown when an invalid argument is used.</exception>
110         /// <exception cref="InvalidOperationException">Thrown when invalid operation occurs.</exception>
111         /// <exception cref="UnauthorizedAccessException">Thrown when the app has no privilege to retrieve app history.</exception>
112         public IReadOnlyList<BatteryStatisticsData> Query(DateTime startTime, DateTime endTime, uint resultSize)
113         {
114             CheckTimeSpan(startTime, endTime);
115             CheckResultSize(resultSize);
116
117             List<BatteryStatisticsData> result = new List<BatteryStatisticsData>();
118
119             IntPtr cursor = IntPtr.Zero;
120             int error = Interop.CtxHistory.Query(Uri, (int)ConvertDateTimeToUnixTimestamp(startTime), (int)ConvertDateTimeToUnixTimestamp(endTime), resultSize, out cursor);
121             if ((AppHistoryError)error == AppHistoryError.NoData)
122             {
123                 return result.AsReadOnly();
124             }
125             else if ((AppHistoryError)error != AppHistoryError.None)
126             {
127                 Log.Error(AppHistoryErrorFactory.LogTag, "Failed to request query battery statistics");
128                 throw AppHistoryErrorFactory.CheckAndThrowException((AppHistoryError)error, "Failed to request query battery statistics");
129             }
130
131             int size;
132             error = Interop.CtxHistoryCursor.GetCount(cursor, out size);
133             Interop.CtxHistoryCursor.First(cursor);
134
135             for (int i = 0; i < size; i++)
136             {
137                 result.Add(ConvertOutputToStatsData(cursor));
138                 Interop.CtxHistoryCursor.Next(cursor);
139             }
140             Interop.CtxHistoryCursor.Destroy(cursor);
141
142             return result.AsReadOnly();
143         }
144
145         /// <summary>
146         /// Gets the last time when the device was fully charged.
147         /// </summary>
148         /// <returns>The last time when the device was fully charged.</returns>
149         /// <feature>http://tizen.org/feature/battery</feature>
150         /// <exception cref="NotSupportedException">Thrown when the statistics is not supported.</exception>
151         public static DateTime GetLastFullyChargedTime()
152         {
153             Int64 timestamp;
154             int error = Interop.CtxHistory.GetLastFullyChargedTime(out timestamp);
155             if ((AppHistoryError)error != AppHistoryError.None)
156             {
157                 Log.Error(AppHistoryErrorFactory.LogTag, "Failed to request get last fully charged time");
158                 throw AppHistoryErrorFactory.CheckAndThrowException((AppHistoryError)error, "Failed to request get last fully charged time");
159             }
160
161             return ConvertUnixTimestampToDateTime(timestamp);
162         }
163
164         internal override string ConvertSortOrderToString(int order)
165         {
166             switch ((SortOrderType)order)
167             {
168                 case SortOrderType.ConsumptionMost:
169                     return "stats/battery/history";
170                 default:
171                     return null;
172             }
173         }
174
175         private static BatteryStatisticsData ConvertOutputToStatsData(IntPtr cursor)
176         {
177             string appId;
178             double consumption;
179
180             Interop.CtxHistoryCursor.GetString(cursor, AppStatsAppId, out appId);
181             Interop.CtxHistoryCursor.GetDouble(cursor, AppStatsConsumption, out consumption);
182
183             return new BatteryStatisticsData(appId, consumption);
184         }
185
186         /// <summary>
187         /// Gets the criteria of battery statistics sorted by.
188         /// </summary>
189         /// <value>The criteria of battery statistics sorted by.</value>
190         public SortOrderType SortOrder { get; private set; }
191
192         /// <summary>
193         /// Sort order type of battery statistics.
194         /// </summary>
195         public enum SortOrderType
196         {
197             /// <summary>
198             /// Sorts apps by consumption, the most battery consuming apps appear first. (Default)
199             /// </summary>
200             ConsumptionMost = 0
201         }
202     }
203 }