summaryrefslogtreecommitdiffstats
path: root/src/com/cyanogenmod/lockclock/preference/CustomLocationPreference.java
blob: c290cf5b61286be8093ff49b31d1476871ad7fd2 (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
/*
 * Copyright (C) 2012 The CyanogenMod Project (DvTonder)
 *
 * 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.cyanogenmod.lockclock.preference;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.preference.EditTextPreference;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.cyanogenmod.lockclock.R;
import com.cyanogenmod.lockclock.misc.Preferences;
import cyanogenmod.weather.CMWeatherManager;
import cyanogenmod.weather.WeatherLocation;

import java.util.HashSet;
import java.util.List;

public class CustomLocationPreference extends EditTextPreference
        implements CMWeatherManager.LookupCityRequestListener {
    public CustomLocationPreference(Context context) {
        super(context);
    }
    public CustomLocationPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public CustomLocationPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    private ProgressDialog mProgressDialog;
    private int mCustomLocationRequestId;
    private Handler mHandler;
    @Override
    protected void showDialog(Bundle state) {
        super.showDialog(state);
        mHandler = new Handler(getContext().getMainLooper());

        final AlertDialog d = (AlertDialog) getDialog();
        final Button okButton = d.getButton(DialogInterface.BUTTON_POSITIVE);
        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomLocationPreference.this.onClick(d, DialogInterface.BUTTON_POSITIVE);
                final String customLocationToLookUp = getEditText().getText().toString();
                if (TextUtils.equals(customLocationToLookUp, "")) return;
                final CMWeatherManager weatherManager = CMWeatherManager.getInstance(getContext());
                mProgressDialog = new ProgressDialog(getContext());
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                mProgressDialog.setMessage(getContext().getString(R.string.weather_progress_title));
                mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        weatherManager.cancelRequest(mCustomLocationRequestId);
                    }
                });
                mCustomLocationRequestId = weatherManager.lookupCity(customLocationToLookUp,
                        CustomLocationPreference.this);
                mProgressDialog.show();
            }
        });
    }

    @Override
    protected void onBindDialogView(View view) {
        super.onBindDialogView(view);

        String location = Preferences.getCustomWeatherLocationCity(getContext());
        if (location != null) {
            getEditText().setText(location);
            getEditText().setSelection(location.length());
        } else {
            getEditText().setText("");
        }
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        // we handle persisting the selected location below, so pretend cancel
        super.onDialogClosed(false);
    }

    private void handleResultDisambiguation(final List<WeatherLocation> results) {
        CharSequence[] items = buildItemList(results);
        new AlertDialog.Builder(getContext())
                .setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        applyLocation(results.get(which));
                        dialog.dismiss();
                    }
                })
                .setNegativeButton(android.R.string.cancel, null)
                .setTitle(R.string.weather_select_location)
                .show();
    }

    private CharSequence[] buildItemList(List<WeatherLocation> results) {
        boolean needCountry = false, needPostal = false;
        String countryId = results.get(0).getCountryId();
        HashSet<String> postalIds = new HashSet<>();

        for (WeatherLocation result : results) {
            if (!TextUtils.equals(result.getCountryId(), countryId)) {
                needCountry = true;
            }
            String postalId = result.getCountryId() + "##" + result.getCity();
            if (postalIds.contains(postalId)) {
                needPostal = true;
            }
            postalIds.add(postalId);
            if (needPostal && needCountry) {
                break;
            }
        }

        int count = results.size();
        CharSequence[] items = new CharSequence[count];
        for (int i = 0; i < count; i++) {
            WeatherLocation result = results.get(i);
            StringBuilder builder = new StringBuilder();
            if (needPostal && result.getPostalCode() != null) {
                builder.append(result.getPostalCode()).append(" ");
            }
            builder.append(result.getCity());
            if (needCountry) {
                String country = result.getCountry() != null
                        ? result.getCountry() : result.getCountryId();
                builder.append(" (").append(country).append(")");
            }
            items[i] = builder.toString();
        }
        return items;
    }

    private void applyLocation(final WeatherLocation result) {
        if (Preferences.setCustomWeatherLocation(getContext(), result)) {
            String cityName = result.getCity();
            String state = result.getState();
            String country = result.getCountry();
            setText(cityName + "," + state + "/" + country);
        }
        final AlertDialog d = (AlertDialog) getDialog();
        d.dismiss();
    }

    @Override
    public void onLookupCityRequestCompleted(int status, final List<WeatherLocation> locations) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                final Context context = getContext();
                if (locations == null || locations.isEmpty()) {
                    Toast.makeText(context,
                            context.getString(R.string.weather_retrieve_location_dialog_title),
                            Toast.LENGTH_SHORT)
                            .show();
                } else if (locations.size() > 1) {
                    handleResultDisambiguation(locations);
                } else {
                    applyLocation(locations.get(0));
                }
                mProgressDialog.dismiss();
            }
        });
    }
}