1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5 * except in compliance with the License. You may obtain a copy of the License at
6 *
7 *      http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
11 * KIND, either express or implied. See the License for the specific language governing
12 * permissions and limitations under the License.
13 */
14
15package com.android.settings.fuelgauge;
16
17import android.os.BatteryStats.HistoryItem;
18import android.util.SparseBooleanArray;
19import android.util.SparseIntArray;
20import com.android.settings.fuelgauge.BatteryActiveView.BatteryActiveProvider;
21import com.android.settingslib.BatteryInfo;
22
23public class BatteryFlagParser implements BatteryInfo.BatteryDataParser, BatteryActiveProvider {
24
25    private final SparseBooleanArray mData = new SparseBooleanArray();
26    private final int mFlag;
27    private final boolean mState2;
28    private final int mAccentColor;
29
30    private boolean mLastSet;
31    private long mLength;
32    private long mLastTime;
33
34    public BatteryFlagParser(int accent, boolean state2, int flag) {
35        mAccentColor = accent;
36        mFlag = flag;
37        mState2 = state2;
38    }
39
40    protected boolean isSet(HistoryItem record) {
41        return ((mState2 ? record.states2 : record.states) & mFlag) != 0;
42    }
43
44    @Override
45    public void onParsingStarted(long startTime, long endTime) {
46        mLength = endTime - startTime;
47    }
48
49    @Override
50    public void onDataPoint(long time, HistoryItem record) {
51        boolean isSet = isSet(record);
52        if (isSet != mLastSet) {
53            mData.put((int) time, isSet);
54            mLastSet = isSet;
55        }
56        mLastTime = time;
57    }
58
59    @Override
60    public void onDataGap() {
61        if (mLastSet) {
62            mData.put((int) mLastTime, false);
63            mLastSet = false;
64        }
65    }
66
67    @Override
68    public void onParsingDone() {
69        if (mLastSet) {
70            mData.put((int) mLastTime, false);
71            mLastSet = false;
72        }
73    }
74
75    @Override
76    public long getPeriod() {
77        return mLength;
78    }
79
80    @Override
81    public boolean hasData() {
82        return mData.size() > 1;
83    }
84
85    @Override
86    public SparseIntArray getColorArray() {
87        SparseIntArray ret = new SparseIntArray();
88        for (int i = 0; i < mData.size(); i++) {
89            ret.put(mData.keyAt(i), getColor(mData.valueAt(i)));
90        }
91        return ret;
92    }
93
94    private int getColor(boolean b) {
95        if (b) {
96            return mAccentColor;
97        }
98        return 0;
99    }
100}
101