1/*
2 * Copyright (C) 2016 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.settings.datetime;
18
19import android.content.Context;
20import android.provider.Settings;
21import android.support.v7.preference.Preference;
22
23import com.android.settings.core.PreferenceControllerMixin;
24import com.android.settingslib.RestrictedLockUtils;
25import com.android.settingslib.RestrictedSwitchPreference;
26import com.android.settingslib.core.AbstractPreferenceController;
27
28public class AutoTimePreferenceController extends AbstractPreferenceController
29        implements PreferenceControllerMixin, Preference.OnPreferenceChangeListener {
30
31    private static final String KEY_AUTO_TIME = "auto_time";
32    private final UpdateTimeAndDateCallback mCallback;
33
34    public AutoTimePreferenceController(Context context, UpdateTimeAndDateCallback callback) {
35        super(context);
36        mCallback = callback;
37    }
38
39    @Override
40    public boolean isAvailable() {
41        return true;
42    }
43
44    @Override
45    public void updateState(Preference preference) {
46        if (!(preference instanceof RestrictedSwitchPreference)) {
47            return;
48        }
49        ((RestrictedSwitchPreference) preference).setDisabledByAdmin(
50                getEnforcedAdminProperty());
51        ((RestrictedSwitchPreference) preference).setChecked(isEnabled());
52    }
53
54    @Override
55    public String getPreferenceKey() {
56        return KEY_AUTO_TIME;
57    }
58
59    @Override
60    public boolean onPreferenceChange(Preference preference, Object newValue) {
61        boolean autoEnabled = (Boolean) newValue;
62        Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AUTO_TIME,
63                autoEnabled ? 1 : 0);
64        mCallback.updateTimeAndDateDisplay(mContext);
65        return true;
66    }
67
68    public boolean isEnabled() {
69        return Settings.Global.getInt(mContext.getContentResolver(),
70                Settings.Global.AUTO_TIME, 0) > 0;
71    }
72
73    private RestrictedLockUtils.EnforcedAdmin getEnforcedAdminProperty() {
74        return RestrictedLockUtils.checkIfAutoTimeRequired(mContext);
75    }
76}
77