1/*
2 * Copyright (C) 2012 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
17package com.android.deskclock.timer;
18
19import android.content.SharedPreferences;
20import android.os.Parcel;
21import android.os.Parcelable;
22import android.util.Log;
23import android.view.View;
24
25import com.android.deskclock.Utils;
26
27import java.util.ArrayList;
28import java.util.Collections;
29import java.util.Comparator;
30import java.util.HashSet;
31import java.util.Iterator;
32import java.util.Set;
33
34public class TimerObj implements Parcelable {
35
36    private static final String TAG = "TimerObj";
37    // Max timer length is 9 hours + 99 minutes + 9 seconds
38    private static final long MAX_TIMER_LENGTH = (9 * 3600 + 99 * 60  + 60) * 1000;
39
40    public int mTimerId;             // Unique id
41    public long mStartTime;          // With mTimeLeft , used to calculate the correct time
42    public long mTimeLeft;           // in the timer.
43    public long mOriginalLength;     // length set at start of timer and by +1 min after times up
44    public long mSetupLength;        // length set at start of timer
45    public View mView;
46    public int mState;
47    public String mLabel;
48
49    public static final int STATE_RUNNING = 1;
50    public static final int STATE_STOPPED = 2;
51    public static final int STATE_TIMESUP = 3;
52    public static final int STATE_DONE = 4;
53    public static final int STATE_RESTART = 5;
54
55    private static final String PREF_TIMER_ID = "timer_id_";
56    private static final String PREF_START_TIME  = "timer_start_time_";
57    private static final String PREF_TIME_LEFT = "timer_time_left_";
58    private static final String PREF_ORIGINAL_TIME = "timer_original_timet_";
59    private static final String PREF_SETUP_TIME = "timer_setup_timet_";
60    private static final String PREF_STATE = "timer_state_";
61    private static final String PREF_LABEL = "timer_label_";
62
63    private static final String PREF_TIMERS_LIST = "timers_list";
64
65    public static final Parcelable.Creator<TimerObj> CREATOR = new Parcelable.Creator<TimerObj>() {
66        @Override
67        public TimerObj createFromParcel(Parcel p) {
68            return new TimerObj(p);
69        }
70
71        @Override
72        public TimerObj[] newArray(int size) {
73            return new TimerObj[size];
74        }
75    };
76
77    public void writeToSharedPref(SharedPreferences prefs) {
78        SharedPreferences.Editor editor = prefs.edit();
79        String key = PREF_TIMER_ID + Integer.toString(mTimerId);
80        String id = Integer.toString(mTimerId);
81        editor.putInt (key, mTimerId);
82        key = PREF_START_TIME + id;
83        editor.putLong (key, mStartTime);
84        key = PREF_TIME_LEFT + id;
85        editor.putLong (key, mTimeLeft);
86        key = PREF_ORIGINAL_TIME + id;
87        editor.putLong (key, mOriginalLength);
88        key = PREF_SETUP_TIME + id;
89        editor.putLong (key, mSetupLength);
90        key = PREF_STATE + id;
91        editor.putInt (key, mState);
92        Set <String> timersList = prefs.getStringSet(PREF_TIMERS_LIST, new HashSet<String>());
93        timersList.add(id);
94        editor.putStringSet(PREF_TIMERS_LIST, timersList);
95        key = PREF_LABEL + id;
96        editor.putString(key, mLabel);
97        editor.apply();
98    }
99
100
101    public void readFromSharedPref(SharedPreferences prefs) {
102        String id = Integer.toString(mTimerId);
103        String key = PREF_START_TIME + id;
104        mStartTime = prefs.getLong(key, 0);
105        key = PREF_TIME_LEFT + id;
106        mTimeLeft = prefs.getLong(key, 0);
107        key = PREF_ORIGINAL_TIME + id;
108        mOriginalLength = prefs.getLong(key, 0);
109        key = PREF_SETUP_TIME + id;
110        mSetupLength = prefs.getLong(key, 0);
111        key = PREF_STATE + id;
112        mState = prefs.getInt(key, 0);
113        key = PREF_LABEL + id;
114        mLabel = prefs.getString(key, "");
115    }
116
117    public void deleteFromSharedPref(SharedPreferences prefs) {
118        SharedPreferences.Editor editor = prefs.edit();
119        String key = PREF_TIMER_ID + Integer.toString(mTimerId);
120        String id = Integer.toString(mTimerId);
121        editor.remove (key);
122        key = PREF_START_TIME + id;
123        editor.remove (key);
124        key = PREF_TIME_LEFT + id;
125        editor.remove (key);
126        key = PREF_ORIGINAL_TIME + id;
127        editor.remove (key);
128        key = PREF_STATE + id;
129        editor.remove (key);
130        Set <String> timersList = prefs.getStringSet(PREF_TIMERS_LIST, new HashSet<String>());
131        timersList.remove(id);
132        editor.putStringSet(PREF_TIMERS_LIST, timersList);
133        key = PREF_LABEL + id;
134        editor.remove(key);
135        editor.commit();
136        //dumpTimersFromSharedPrefs(prefs);
137    }
138
139
140    @Override
141    public int describeContents() {
142        return 0;
143    }
144
145    @Override
146    public void writeToParcel(Parcel dest, int flags) {
147        dest.writeInt(mTimerId);
148        dest.writeLong(mStartTime);
149        dest.writeLong(mTimeLeft);
150        dest.writeLong(mOriginalLength);
151        dest.writeLong(mSetupLength);
152        dest.writeInt(mState);
153        dest.writeString(mLabel);
154    }
155
156    public TimerObj(Parcel p) {
157        mTimerId = p.readInt();
158        mStartTime = p.readLong();
159        mTimeLeft = p.readLong();
160        mOriginalLength = p.readLong();
161        mSetupLength = p.readLong();
162        mState = p.readInt();
163        mLabel = p.readString();
164    }
165
166    public TimerObj() {
167        init(0);
168    }
169
170    public TimerObj(long timerLength) {
171      init(timerLength);
172    }
173
174    private void init (long length) {
175        mTimerId = (int) Utils.getTimeNow();
176        mStartTime = Utils.getTimeNow();
177        mTimeLeft = mOriginalLength = mSetupLength = length;
178        mLabel = "";
179    }
180
181    public long updateTimeLeft(boolean forceUpdate) {
182        if (isTicking() || forceUpdate) {
183            long millis = Utils.getTimeNow();
184            mTimeLeft = mOriginalLength - (millis - mStartTime);
185        }
186        return mTimeLeft;
187    }
188
189    public boolean isTicking() {
190        return mState == STATE_RUNNING || mState == STATE_TIMESUP;
191    }
192
193    public boolean isInUse() {
194        return mState == STATE_RUNNING || mState == STATE_STOPPED;
195    }
196
197    public void addTime(long time) {
198        mTimeLeft = mOriginalLength - (Utils.getTimeNow() - mStartTime);
199        if (mTimeLeft < MAX_TIMER_LENGTH - time) {
200                mOriginalLength += time;
201        }
202    }
203
204    public long getTimesupTime() {
205        return mStartTime + mOriginalLength;
206    }
207
208
209    public static void getTimersFromSharedPrefs(
210            SharedPreferences prefs, ArrayList<TimerObj> timers) {
211        Object[] timerStrings =
212                prefs.getStringSet(PREF_TIMERS_LIST, new HashSet<String>()).toArray();
213        if (timerStrings.length > 0) {
214            for (int i = 0; i < timerStrings.length; i++) {
215                TimerObj t = new TimerObj();
216                t.mTimerId = Integer.parseInt((String)timerStrings[i]);
217                t.readFromSharedPref(prefs);
218                timers.add(t);
219            }
220            Collections.sort(timers, new Comparator<TimerObj>() {
221                @Override
222                public int compare(TimerObj timerObj1, TimerObj timerObj2) {
223                   return timerObj2.mTimerId - timerObj1.mTimerId;
224                }
225            });
226        }
227    }
228
229    public static void getTimersFromSharedPrefs(
230            SharedPreferences prefs, ArrayList<TimerObj> timers, int match) {
231        Object[] timerStrings = prefs.getStringSet(PREF_TIMERS_LIST, new HashSet<String>())
232                .toArray();
233        if (timerStrings.length > 0) {
234            for (int i = 0; i < timerStrings.length; i++) {
235                TimerObj t = new TimerObj();
236                t.mTimerId = Integer.parseInt((String) timerStrings[i]);
237                t.readFromSharedPref(prefs);
238                if (t.mState == match) {
239                    timers.add(t);
240                }
241            }
242        }
243    }
244
245    public static void putTimersInSharedPrefs(
246            SharedPreferences prefs, ArrayList<TimerObj> timers) {
247        if (timers.size() > 0) {
248            for (int i = 0; i < timers.size(); i++) {
249                TimerObj t = timers.get(i);
250                timers.get(i).writeToSharedPref(prefs);
251            }
252        }
253    }
254
255    public static void dumpTimersFromSharedPrefs(
256            SharedPreferences prefs) {
257        Object[] timerStrings =
258                prefs.getStringSet(PREF_TIMERS_LIST, new HashSet<String>()).toArray();
259        Log.v(TAG,"--------------------- timers list in shared prefs");
260        if (timerStrings.length > 0) {
261            for (int i = 0; i < timerStrings.length; i++) {
262                int id = Integer.parseInt((String)timerStrings[i]);
263                Log.v(TAG,"---------------------timer  " + (i + 1) + ": id - " + id);
264            }
265        }
266    }
267
268    public static void cleanTimersFromSharedPrefs(SharedPreferences prefs) {
269        ArrayList<TimerObj> timers = new  ArrayList<TimerObj>();
270        getTimersFromSharedPrefs(prefs, timers);
271        Iterator<TimerObj> i = timers.iterator();
272        while(i.hasNext()) {
273            i.next().deleteFromSharedPref(prefs);
274        }
275    }
276
277}
278