TimerDAO.java revision 6d603b7c62bb38d763a681a8bf20fadb1442e833
1/*
2 * Copyright (C) 2015 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.data;
18
19import android.content.Context;
20import android.content.SharedPreferences;
21import android.preference.PreferenceManager;
22
23import com.android.deskclock.data.Timer.State;
24
25import java.util.ArrayList;
26import java.util.Collections;
27import java.util.HashSet;
28import java.util.List;
29import java.util.Set;
30
31import static com.android.deskclock.data.Timer.State.RESET;
32
33/**
34 * This class encapsulates the transfer of data between {@link Timer} domain objects and their
35 * permanent storage in {@link SharedPreferences}.
36 */
37final class TimerDAO {
38
39    // Key to a preference that stores the set of timer ids.
40    private static final String TIMER_IDS = "timers_list";
41
42    // Key to a preference that stores the id to assign to the next timer.
43    private static final String NEXT_TIMER_ID = "next_timer_id";
44
45    // Prefix for a key to a preference that stores the state of the timer.
46    private static final String STATE = "timer_state_";
47
48    // Prefix for a key to a preference that stores the length of the timer when it was created.
49    private static final String LENGTH = "timer_setup_timet_";
50
51    // Prefix for a key to a preference that stores the total length of the timer with additions.
52    private static final String TOTAL_LENGTH = "timer_original_timet_";
53
54    // Prefix for a key to a preference that stores the last start time of the timer.
55    private static final String LAST_START_TIME = "timer_start_time_";
56
57    // Prefix for a key to a preference that stores the remaining time before expiry.
58    private static final String REMAINING_TIME = "timer_time_left_";
59
60    // Prefix for a key to a preference that stores the label of the timer.
61    private static final String LABEL = "timer_label_";
62
63    // Prefix for a key to a preference that signals the timer should be deleted on first reset.
64    private static final String DELETE_AFTER_USE = "delete_after_use_";
65
66    // Lazily instantiated and cached for the life of the application.
67    private static SharedPreferences sPrefs;
68
69    private TimerDAO() {}
70
71    /**
72     * @return the timers from permanent storage
73     */
74    public static List<Timer> getTimers(Context context) {
75        final SharedPreferences prefs = getSharedPreferences(context);
76
77        // Read the set of timer ids.
78        final Set<String> timerIds = prefs.getStringSet(TIMER_IDS, Collections.<String>emptySet());
79        final List<Timer> timers = new ArrayList<>(timerIds.size());
80
81        // Build a timer using the data associated with each timer id.
82        for (String timerId : timerIds) {
83            final int id = Integer.parseInt(timerId);
84            final int stateValue = prefs.getInt(STATE + id, RESET.getValue());
85            final State state = State.fromValue(stateValue);
86            final long length = prefs.getLong(LENGTH + id, Long.MIN_VALUE);
87            final long totalLength = prefs.getLong(TOTAL_LENGTH + id, Long.MIN_VALUE);
88            final long lastStartTime = prefs.getLong(LAST_START_TIME + id, Long.MIN_VALUE);
89            final long remainingTime = prefs.getLong(REMAINING_TIME + id, totalLength);
90            final String label = prefs.getString(LABEL + id, null);
91            final boolean deleteAfterUse = prefs.getBoolean(DELETE_AFTER_USE + id, false);
92            timers.add(new Timer(id, state, length, totalLength, lastStartTime, remainingTime,
93                    label, deleteAfterUse));
94        }
95
96        return timers;
97    }
98
99    /**
100     * @param timer the timer to be added
101     */
102    public static Timer addTimer(Context context, Timer timer) {
103        final SharedPreferences prefs = getSharedPreferences(context);
104        final SharedPreferences.Editor editor = prefs.edit();
105
106        // Fetch the next timer id.
107        final int id = prefs.getInt(NEXT_TIMER_ID, 0);
108        editor.putInt(NEXT_TIMER_ID, id + 1);
109
110        // Add the new timer id to the set of all timer ids.
111        final Set<String> timerIds = new HashSet<>(getTimerIds(context));
112        timerIds.add(String.valueOf(id));
113        editor.putStringSet(TIMER_IDS, timerIds);
114
115        // Record the fields of the timer.
116        editor.putInt(STATE + id, timer.getState().getValue());
117        editor.putLong(LENGTH + id, timer.getLength());
118        editor.putLong(TOTAL_LENGTH + id, timer.getTotalLength());
119        editor.putLong(LAST_START_TIME + id, timer.getLastStartTime());
120        editor.putLong(REMAINING_TIME + id, timer.getRemainingTime());
121        editor.putString(LABEL + id, timer.getLabel());
122        editor.putBoolean(DELETE_AFTER_USE + id, timer.getDeleteAfterUse());
123
124        editor.apply();
125
126        // Return a new timer with the generated timer id present.
127        return new Timer(id, timer.getState(), timer.getLength(), timer.getTotalLength(),
128                timer.getLastStartTime(), timer.getRemainingTime(), timer.getLabel(),
129                timer.getDeleteAfterUse());
130    }
131
132    /**
133     * @param timer the timer to be updated
134     */
135    public static void updateTimer(Context context, Timer timer) {
136        final SharedPreferences prefs = getSharedPreferences(context);
137        final SharedPreferences.Editor editor = prefs.edit();
138
139        // Record the fields of the timer.
140        final int id = timer.getId();
141        editor.putInt(STATE + id, timer.getState().getValue());
142        editor.putLong(LENGTH + id, timer.getLength());
143        editor.putLong(TOTAL_LENGTH + id, timer.getTotalLength());
144        editor.putLong(LAST_START_TIME + id, timer.getLastStartTime());
145        editor.putLong(REMAINING_TIME + id, timer.getRemainingTime());
146        editor.putString(LABEL + id, timer.getLabel());
147        editor.putBoolean(DELETE_AFTER_USE + id, timer.getDeleteAfterUse());
148
149        editor.apply();
150    }
151
152    /**
153     * @param timer the timer to be removed
154     */
155    public static void removeTimer(Context context, Timer timer) {
156        final SharedPreferences prefs = getSharedPreferences(context);
157        final SharedPreferences.Editor editor = prefs.edit();
158
159        final int id = timer.getId();
160
161        // Remove the timer id from the set of all timer ids.
162        final Set<String> timerIds = new HashSet<>(getTimerIds(context));
163        timerIds.remove(String.valueOf(id));
164        if (timerIds.isEmpty()) {
165            editor.remove(TIMER_IDS);
166            editor.remove(NEXT_TIMER_ID);
167        } else {
168            editor.putStringSet(TIMER_IDS, timerIds);
169        }
170
171        // Record the fields of the timer.
172        editor.remove(STATE + id);
173        editor.remove(LENGTH + id);
174        editor.remove(TOTAL_LENGTH + id);
175        editor.remove(LAST_START_TIME + id);
176        editor.remove(REMAINING_TIME + id);
177        editor.remove(LABEL + id);
178        editor.remove(DELETE_AFTER_USE + id);
179
180        editor.apply();
181    }
182
183    private static Set<String> getTimerIds(Context context) {
184        final SharedPreferences prefs = getSharedPreferences(context);
185        return prefs.getStringSet(TIMER_IDS, Collections.<String>emptySet());
186    }
187
188    private static SharedPreferences getSharedPreferences(Context context) {
189        if (sPrefs == null) {
190            sPrefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
191        }
192
193        return sPrefs;
194    }
195}