summaryrefslogtreecommitdiffstats
path: root/src/com/android/deskclock/HandleDeskClockApiCalls.java
blob: 2e59b09256590c941215fd8a9727dbfba0ee4ca1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.deskclock;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;

import com.android.deskclock.data.City;
import com.android.deskclock.data.DataModel;
import com.android.deskclock.events.Events;
import com.android.deskclock.stopwatch.StopwatchService;
import com.android.deskclock.stopwatch.Stopwatches;
import com.android.deskclock.timer.TimerFullScreenFragment;
import com.android.deskclock.timer.TimerObj;
import com.android.deskclock.timer.Timers;
import com.android.deskclock.worldclock.CitySelectionActivity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class HandleDeskClockApiCalls extends Activity {
    private Context mAppContext;

    private static final String ACTION_PREFIX = "com.android.deskclock.action.";

    // shows the tab with world clocks
    public static final String ACTION_SHOW_CLOCK = ACTION_PREFIX + "SHOW_CLOCK";
    // extra for ACTION_SHOW_CLOCK indicating the clock is being displayed from tapping the widget
    public static final String EXTRA_FROM_WIDGET = "com.android.deskclock.extra.clock.FROM_WIDGET";
    // add a clock of a selected city, if no city is specified opens the city selection screen
    public static final String ACTION_ADD_CLOCK = ACTION_PREFIX + "ADD_CLOCK";
    // delete a clock of a selected city, if no city is specified shows CitiesActivity for the user
    // to choose a city
    public static final String ACTION_DELETE_CLOCK = ACTION_PREFIX + "DELETE_CLOCK";
    // extra for ACTION_ADD_CLOCK and ACTION_DELETE_CLOCK
    public static final String EXTRA_CITY = "com.android.deskclock.extra.clock.CITY";

    // shows the tab with the stopwatch
    public static final String ACTION_SHOW_STOPWATCH = ACTION_PREFIX + "SHOW_STOPWATCH";
    // starts the current stopwatch
    public static final String ACTION_START_STOPWATCH = ACTION_PREFIX + "START_STOPWATCH";
    // stops the current stopwatch
    public static final String ACTION_STOP_STOPWATCH = ACTION_PREFIX + "STOP_STOPWATCH";
    // laps the stopwatch that's currently running
    public static final String ACTION_LAP_STOPWATCH = ACTION_PREFIX + "LAP_STOPWATCH";
    // resets the stopwatch if it's stopped
    public static final String ACTION_RESET_STOPWATCH = ACTION_PREFIX + "RESET_STOPWATCH";

    // shows the tab with timers
    public static final String ACTION_SHOW_TIMERS = ACTION_PREFIX + "SHOW_TIMERS";
    // deletes the topmost timer
    public static final String ACTION_DELETE_TIMER = ACTION_PREFIX + "DELETE_TIMER";
    // stops the running timer
    public static final String ACTION_STOP_TIMER = ACTION_PREFIX + "STOP_TIMER";
    // starts the topmost timer
    public static final String ACTION_START_TIMER = ACTION_PREFIX + "START_TIMER";
    // resets the timer, works for both running and stopped
    public static final String ACTION_RESET_TIMER = ACTION_PREFIX + "RESET_TIMER";

    @Override
    protected void onCreate(Bundle icicle) {
        try {
            super.onCreate(icicle);
            mAppContext = getApplicationContext();

            final Intent intent = getIntent();
            if (intent == null) {
                return;
            }

            final String action = intent.getAction();
            switch (action) {
                case ACTION_START_STOPWATCH:
                case ACTION_STOP_STOPWATCH:
                case ACTION_LAP_STOPWATCH:
                case ACTION_SHOW_STOPWATCH:
                case ACTION_RESET_STOPWATCH:
                    handleStopwatchIntent(action);
                    break;
                case ACTION_SHOW_TIMERS:
                case ACTION_DELETE_TIMER:
                case ACTION_RESET_TIMER:
                case ACTION_STOP_TIMER:
                case ACTION_START_TIMER:
                    handleTimerIntent(action);
                    break;
                case ACTION_SHOW_CLOCK:
                case ACTION_ADD_CLOCK:
                case ACTION_DELETE_CLOCK:
                    handleClockIntent(action);
                    break;
            }
        } finally {
            finish();
        }
    }

    private void handleStopwatchIntent(String action) {
        // Opens the UI for stopwatch
        final Intent stopwatchIntent = new Intent(mAppContext, DeskClock.class)
                .setAction(action)
                .putExtra(DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.STOPWATCH_TAB_INDEX);
        startActivity(stopwatchIntent);
        LogUtils.i("HandleDeskClockApiCalls " + action);

        if (action.equals(ACTION_SHOW_STOPWATCH)) {
            Events.sendStopwatchEvent(R.string.action_show, R.string.label_intent);
            return;
        }

        // checking if the stopwatch is already running
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mAppContext);
        final boolean stopwatchAlreadyRunning =
                prefs.getBoolean(Stopwatches.NOTIF_CLOCK_RUNNING, false);

        if (stopwatchAlreadyRunning) {
            // don't fire START_STOPWATCH or RESET_STOPWATCH if a stopwatch is already running
            if (ACTION_START_STOPWATCH.equals(action)) {
                final String reason = getString(R.string.stopwatch_already_running);
                Voice.notifyFailure(this, reason);
                LogUtils.i(reason);
                return;
            } else if (ACTION_RESET_STOPWATCH.equals(action)) { // RESET_STOPWATCH
                final String reason = getString(R.string.stopwatch_cant_be_reset_because_is_running);
                Voice.notifyFailure(this, reason);
                LogUtils.i(reason);
                return;
            }
        } else {
            // if a stopwatch isn't running, don't try to stop or lap it
            if (ACTION_STOP_STOPWATCH.equals(action) ||
                    ACTION_LAP_STOPWATCH.equals(action)) {
                final String reason = getString(R.string.stopwatch_isnt_running);
                Voice.notifyFailure(this, reason);
                LogUtils.i(reason);
                return;
            }
        }

        final String reason;
        // Events and voice interactor setup
        switch (action) {
            case ACTION_START_STOPWATCH:
                Events.sendStopwatchEvent(R.string.action_start, R.string.label_intent);
                reason = getString(R.string.stopwatch_started);
                break;
            case ACTION_STOP_STOPWATCH:
                Events.sendStopwatchEvent(R.string.action_stop, R.string.label_intent);
                reason = getString(R.string.stopwatch_stopped);
                break;
            case ACTION_LAP_STOPWATCH:
                Events.sendStopwatchEvent(R.string.action_lap, R.string.label_intent);
                reason = getString(R.string.stopwatch_lapped);
                break;
            case ACTION_RESET_STOPWATCH:
                Events.sendStopwatchEvent(R.string.action_reset, R.string.label_intent);
                reason = getString(R.string.stopwatch_reset);
                break;
            default:
                return;
        }
        final Intent intent = new Intent(mAppContext, StopwatchService.class).setAction(action);
        startService(intent);
        Voice.notifySuccess(this, reason);
        LogUtils.i(reason);
    }

    private void handleTimerIntent(final String action) {
        // Opens the UI for timers
        final Intent timerIntent = new Intent(mAppContext, DeskClock.class)
                .putExtra(DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.TIMER_TAB_INDEX)
                .putExtra(TimerFullScreenFragment.GOTO_SETUP_VIEW, false);
        startActivity(timerIntent);
        LogUtils.i("HandleDeskClockApiCalls " + action);

        if (ACTION_SHOW_TIMERS.equals(action)) {
            Events.sendTimerEvent(R.string.action_show, R.string.label_intent);
            return;
        }
        new HandleTimersAsync(mAppContext, action, this).execute();
    }

    private void handleClockIntent(final String action) {
        // Opens the UI for clocks
        final Intent handleClock = new Intent(mAppContext, DeskClock.class)
                .setAction(action)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                .putExtra(DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.CLOCK_TAB_INDEX);
        startActivity(handleClock);

        new HandleClockAsync(mAppContext, getIntent(), this).execute();
    }

    private static class HandleTimersAsync extends AsyncTask<Void, Void, Void> {
        private final Context mContext;
        private final String mAction;
        private final Activity mActivity;

        public HandleTimersAsync(Context context, String action, Activity activity) {
            mContext = context;
            mAction = action;
            mActivity = activity;
        }
        // STOP_TIMER and START_TIMER should only be triggered if there is one timer that is
        // not stopped or not started respectively. This method checks all timers to find only
        // one that corresponds to that.
        // Only change the mode of the timer if no disambiguation is necessary

        @Override
        protected Void doInBackground(Void... parameters) {
            final List<TimerObj> timers = new ArrayList<>();
            final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
            TimerObj.getTimersFromSharedPrefs(prefs, timers);
            if (timers.isEmpty()) {
                final String reason = mContext.getString(R.string.no_timer_set);
                LogUtils.i(reason);
                Voice.notifyFailure(mActivity, reason);
                return null;
            }
            final TimerObj timer;
            final String timerAction;
            switch (mAction) {
                case ACTION_DELETE_TIMER: {
                    timerAction = Timers.DELETE_TIMER;
                    // Delete a timer only if there's one available
                    if (timers.size() > 1) {
                        final String reason = mContext.getString(R.string.multiple_timers_available);
                        LogUtils.i(reason);
                        Voice.notifyFailure(mActivity, reason);
                        return null;
                    }

                    timer = timers.get(0);
                    timer.deleteFromSharedPref(prefs);
                    Events.sendTimerEvent(R.string.action_delete, R.string.label_intent);
                    final String reason = mContext.getString(R.string.timer_deleted);
                    Voice.notifySuccess(mActivity, reason);
                    LogUtils.i(reason);
                    break;
                }
                case ACTION_START_TIMER: {
                    timerAction = Timers.START_TIMER;
                    timer = getTimerWithStateToIgnore(timers, TimerObj.STATE_RUNNING);
                    // Only start a timer if there's one non-running timer available
                    if (timer == null) {
                        // notifyFailure was already triggered
                        return null;
                    }
                    timer.setState(TimerObj.STATE_RUNNING);
                    timer.mStartTime = Utils.getTimeNow() - (timer.mSetupLength - timer.mTimeLeft);
                    timer.writeToSharedPref(prefs);
                    final String reason = mContext.getString(R.string.timer_started);
                    Voice.notifySuccess(mActivity, reason);
                    LogUtils.i(reason);
                    Events.sendTimerEvent(R.string.action_start, R.string.label_intent);
                    break;
                }
                case ACTION_RESET_TIMER: {
                    timerAction = Timers.RESET_TIMER;
                    // Since timer can be reset only if it's stopped
                    // it's only triggered when there's only one stopped timer
                    final Set<Integer> statesToInclude = new HashSet<>();
                    statesToInclude.add(TimerObj.STATE_STOPPED);
                    timer = getTimerWithStatesToInclude(timers, statesToInclude, mAction);
                    if (timer == null) {
                        return null;
                    }
                    final String reason = mContext.getString(R.string.timer_was_reset);
                    Voice.notifySuccess(mActivity, reason);
                    LogUtils.i(reason);
                    timer.setState(TimerObj.STATE_RESTART);
                    timer.mTimeLeft = timer.mSetupLength;
                    timer.writeToSharedPref(prefs);
                    Events.sendTimerEvent(R.string.action_reset, R.string.label_intent);
                    break;
                }
                case ACTION_STOP_TIMER: {
                    timerAction = Timers.STOP_TIMER;
                    final Set<Integer> statesToInclude = new HashSet<>();
                    statesToInclude.add(TimerObj.STATE_TIMESUP);
                    statesToInclude.add(TimerObj.STATE_RUNNING);
                    // Timer is stopped if there's only one running timer
                    timer = getTimerWithStatesToInclude(timers, statesToInclude, mAction);
                    if (timer == null) {
                        return null;
                    }
                    final String reason = mContext.getString(R.string.timer_stopped);
                    LogUtils.i(reason);
                    Voice.notifySuccess(mActivity, reason);
                    if (timer.mState == TimerObj.STATE_RUNNING) {
                        timer.setState(TimerObj.STATE_STOPPED);
                    } else {
                        // if the time is up on the timer
                        // restart it and reset the length
                        timer.setState(TimerObj.STATE_RESTART);
                        timer.mTimeLeft = timer.mSetupLength;
                    }
                    timer.writeToSharedPref(prefs);
                    Events.sendTimerEvent(R.string.action_stop, R.string.label_intent);
                    break;
                }
                default:
                    return null;
            }
            // updating the time for next firing timer
            final Intent i = new Intent()
                    .setAction(timerAction)
                    .putExtra(Timers.TIMER_INTENT_EXTRA, timer.mTimerId)
                    .putExtra(Timers.UPDATE_NEXT_TIMESUP, true)
                    // Make sure the receiver is getting the intent ASAP.
                    .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
            mContext.sendBroadcast(i);
            return null;
        }

        /**
         * @param timers available to the user
         * @param stateToIgnore the opposite of the state that the timer should be in
         * @return a timer only if there's one timer available that is of a state
         * other than the state that's passed
         * in all other cases returns null
         */
        private TimerObj getTimerWithStateToIgnore(List<TimerObj> timers, int stateToIgnore) {
            TimerObj soleTimer = null;
            for (TimerObj timer : timers) {
                if (timer.mState != stateToIgnore) {
                    if (soleTimer == null) {
                        soleTimer = timer;
                    } else {
                        // soleTimer has already been set
                        final String reason = mContext.getString(R.string.multiple_timers_available);
                        LogUtils.i(reason);
                        Voice.notifyFailure(mActivity, reason);
                        return null;
                    }
                }
            }
            return soleTimer;
        }

        /**
         * @param timers available to the user
         * @param statesToInclude acceptable states of the timer
         * @return a timer only if there's one timer available that is of the state
         * that is passed in
         * in all other cases returns null
         */
        private TimerObj getTimerWithStatesToInclude(
                List<TimerObj> timers, Set<Integer> statesToInclude, String action) {
            TimerObj soleTimer = null;
            for (TimerObj timer : timers) {
                if (statesToInclude.contains(timer.mState)) {
                    if (soleTimer == null) {
                        soleTimer = timer;
                    } else {
                        // soleTimer has already been set
                        final String reason = mContext.getString(
                                R.string.multiple_timers_available);
                        LogUtils.i(reason);
                        Voice.notifyFailure(mActivity, reason);
                        return null;
                    }
                }
            }
            // if there are no timers of desired property
            // announce it to the user
            if (soleTimer == null) {
                if (action.equals(ACTION_RESET_TIMER)) {
                    // all timers are running
                    final String reason = mContext.getString(
                            R.string.timer_cant_be_reset_because_its_running);
                    LogUtils.i(reason);
                    Voice.notifyFailure(mActivity, reason);
                } else if (action.equals(ACTION_STOP_TIMER)) {
                    // no running timers
                    final String reason = mContext.getString(R.string.timer_already_stopped);
                    LogUtils.i(reason);
                    Voice.notifyFailure(mActivity, reason);
                }
            }
            return soleTimer;
        }
    }

    private static class HandleClockAsync extends AsyncTask<Void, Void, Void> {
        private final Context mContext;
        private final Intent mIntent;
        private final Activity mActivity;

        public HandleClockAsync(Context context, Intent intent, Activity activity) {
            mContext = context;
            mIntent = intent;
            mActivity = activity;
        }

        @Override
        protected Void doInBackground(Void... parameters) {
            final String cityName = mIntent.getStringExtra(EXTRA_CITY);
            switch (mIntent.getAction()) {
                case ACTION_ADD_CLOCK: {
                    // if a city isn't specified open CitiesActivity to choose a city
                    if (cityName == null) {
                        final String reason = mContext.getString(R.string.no_city_selected);
                        Voice.notifyFailure(mActivity, reason);
                        LogUtils.i(reason);
                        startSelectWorldClocksActivity();
                        Events.sendClockEvent(R.string.action_create, R.string.label_intent);
                        break;
                    }

                    // if a city is passed add that city to the list
                    final City city = DataModel.getDataModel().getCity(cityName);
                    // check if this city exists in the list of available cities
                    if (city == null) {
                        final String reason = mContext.getString(
                                R.string.the_city_you_specified_is_not_available);
                        Voice.notifyFailure(mActivity, reason);
                        LogUtils.i(reason);
                        break;
                    }

                    final Set<City> selectedCities =
                            Utils.newArraySet(DataModel.getDataModel().getSelectedCities());
                    // if this city is already added don't add it
                    if (!selectedCities.add(city)) {
                        final String reason = mContext.getString(R.string.the_city_already_added);
                        Voice.notifyFailure(mActivity, reason);
                        LogUtils.i(reason);
                        break;
                    }

                    DataModel.getDataModel().setSelectedCities(selectedCities);
                    final String reason = mContext.getString(R.string.city_added, city.getName());
                    Voice.notifySuccess(mActivity, reason);
                    LogUtils.i(reason);
                    Events.sendClockEvent(R.string.action_start, R.string.label_intent);
                    break;
                }
                case ACTION_DELETE_CLOCK: {
                    if (cityName == null) {
                        // if a city isn't specified open the activity that chooses a city
                        final String reason = mContext.getString(R.string.no_city_selected);
                        Voice.notifyFailure(mActivity, reason);
                        LogUtils.i(reason);
                        startSelectWorldClocksActivity();
                        Events.sendClockEvent(R.string.action_create, R.string.label_intent);
                        break;
                    }

                    // if a city is specified check if it's selected and if so delete it
                    final City city = DataModel.getDataModel().getCity(cityName);
                    if (city == null) {
                        final String reason = mContext.getString(
                                R.string.the_city_you_specified_is_not_available);
                        Voice.notifyFailure(mActivity, reason);
                        LogUtils.i(reason);
                        break;
                    }

                    final Set<City> selectedCities =
                            Utils.newArraySet(DataModel.getDataModel().getSelectedCities());

                    // check if this city exists in the list of available cities
                    if (!selectedCities.remove(city)) {
                        // the specified city hasn't been added to the user's list yet
                        Voice.notifyFailure(mActivity, mContext.getString(
                                R.string.the_city_you_specified_is_not_available));
                        break;
                    }

                    DataModel.getDataModel().setSelectedCities(selectedCities);
                    final String reason = mContext.getString(R.string.city_deleted, city.getName());
                    Voice.notifySuccess(mActivity, reason);
                    LogUtils.i(reason);
                    Events.sendClockEvent(R.string.action_delete, R.string.label_intent);
                    break;
                }
                case ACTION_SHOW_CLOCK:
                    final boolean fromWidget = mIntent.getBooleanExtra(EXTRA_FROM_WIDGET, false);
                    final int label = fromWidget ? R.string.label_widget : R.string.label_intent;
                    Events.sendClockEvent(R.string.action_show, label);
                    break;
            }
            return null;
        }

        private void startSelectWorldClocksActivity() {
            mContext.startActivity(new Intent(mContext, CitySelectionActivity.class)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        }
    }
}