aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/org/cyanogenmod/wundergroundcmweatherprovider/WundergroundWeatherProviderService.java
blob: 9c698589ce39b0ca5790cf4c501b50e09ae53803 (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
/**
 * Copyright (C) 2016 The CyanogenMod 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 org.cyanogenmod.wundergroundcmweatherprovider;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Message;
import android.util.Log;

import org.cyanogenmod.wundergroundcmweatherprovider.wunderground.ConverterUtils;
import org.cyanogenmod.wundergroundcmweatherprovider.wunderground.Feature;
import org.cyanogenmod.wundergroundcmweatherprovider.wunderground.WundergroundServiceManager;
import org.cyanogenmod.wundergroundcmweatherprovider.wunderground.responses.CurrentObservationResponse;
import org.cyanogenmod.wundergroundcmweatherprovider.wunderground.responses.DisplayLocationResponse;
import org.cyanogenmod.wundergroundcmweatherprovider.wunderground.responses.ForecastResponse;
import org.cyanogenmod.wundergroundcmweatherprovider.wunderground.responses.WundergroundReponse;
import org.cyanogenmod.wundergroundcmweatherprovider.wunderground.responses.forecast.SimpleForecastResponse;

import cyanogenmod.providers.WeatherContract;
import cyanogenmod.weather.RequestInfo;
import cyanogenmod.weather.WeatherInfo;
import cyanogenmod.weatherservice.ServiceRequest;
import cyanogenmod.weatherservice.ServiceRequestResult;
import cyanogenmod.weatherservice.WeatherProviderService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.util.ArrayList;

import javax.inject.Inject;

public class WundergroundWeatherProviderService extends WeatherProviderService {
    private static final String TAG = WundergroundWeatherProviderService.class.getSimpleName();
    private static final int SERVICE_REQUEST_CANCELLED = -1;
    private static final int SERVICE_REQUEST_SUBMITTED = 0;

    @Inject
    public WundergroundServiceManager mWundergroundServiceManager;

    @Override
    public void onCreate() {
        super.onCreate();
        WundergroundCMApplication.get(this).inject(this);
    }

    @Override
    protected void onRequestSubmitted(final ServiceRequest serviceRequest) {
        Log.d(TAG, "Received service request: " + serviceRequest.toString());
        Message request = mHandler.obtainMessage(SERVICE_REQUEST_SUBMITTED, serviceRequest);
        request.sendToTarget();
    }

    @Override
    protected void onRequestCancelled(ServiceRequest serviceRequest) {
        Log.d(TAG, "Received service request cancelled: " + serviceRequest.toString());
        Message request = mHandler.obtainMessage(SERVICE_REQUEST_CANCELLED, serviceRequest);
        request.sendToTarget();
    }

    private final NonLeakyMessageHandler mHandler = new NonLeakyMessageHandler(this);

    private static class NonLeakyMessageHandler
            extends WeakReferenceHandler<WundergroundWeatherProviderService> {
        public NonLeakyMessageHandler(WundergroundWeatherProviderService reference) {
            super(reference);
        }

        @Override
        protected void handleMessage(WundergroundWeatherProviderService reference,
                Message inputMessage) {
            ServiceRequest serviceRequest = (ServiceRequest)inputMessage.obj;
            switch (inputMessage.what) {
                case SERVICE_REQUEST_SUBMITTED:
                    RequestInfo requestInfo = serviceRequest.getRequestInfo();
                    switch (requestInfo.getRequestType()) {
                        case RequestInfo.TYPE_WEATHER_LOCATION_REQ:
                            reference.processWeatherLocationRequest(serviceRequest);
                            break;
                        default:
                            //Don't support anything else, fail.
                            serviceRequest.fail();
                            break;
                    }
                    break;
                case SERVICE_REQUEST_CANCELLED:
                    //TODO; Implement
                    break;
                default:
                    //Don't support anything else, fail.
                    if (serviceRequest != null) {
                        serviceRequest.fail();
                    }
            }
        }
    }

    private void processWeatherLocationRequest(final ServiceRequest serviceRequest) {
        final RequestInfo requestInfo = serviceRequest.getRequestInfo();
        Log.d(TAG, "Received weather request info: " + requestInfo.toString());

        Location location = requestInfo.getLocation();
        if (location == null) {
            LocationManager locationManager = (LocationManager)
                    getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_HIGH);
            location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria
                    , false));
        }

        Call<WundergroundReponse> wundergroundCall =
                mWundergroundServiceManager.query(location.getLatitude(),
                        location.getLongitude(), Feature.conditions, Feature.forecast);

        wundergroundCall.enqueue(new Callback<WundergroundReponse>() {
            @Override
            public void onResponse(Call<WundergroundReponse> call, Response<WundergroundReponse> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "Received response:\n" + response.body().toString());

                    WundergroundReponse wundergroundReponse = response.body();

                    if (wundergroundReponse == null) {
                        Log.d(TAG, "Null wu reponse, return");
                        serviceRequest.fail();
                        return;
                    }

                    CurrentObservationResponse currentObservationResponse =
                            wundergroundReponse.getCurrentObservation();

                    if (currentObservationResponse == null) {
                        Log.d(TAG, "Null co reponse, return");
                        serviceRequest.fail();
                        return;
                    }

                    WeatherInfo.Builder weatherInfoBuilder =
                            new WeatherInfo.Builder(System.currentTimeMillis());

                    weatherInfoBuilder.setTemperature(currentObservationResponse.getTempF()
                                    .floatValue(),
                            WeatherContract.WeatherColumns.TempUnit.FAHRENHEIT);

                    weatherInfoBuilder.setWeatherCondition(
                            WeatherContract.WeatherColumns.WeatherCode.CLOUDY);

                    DisplayLocationResponse displayLocationResponse =
                            currentObservationResponse.getDisplayLocation();

                    if (displayLocationResponse == null) {
                        Log.d(TAG, "Null dl reponse, return");
                        return;
                    }

                    // Set city
                    weatherInfoBuilder.setCity(displayLocationResponse.getCity(),
                            displayLocationResponse.getCity());

                    // Set humidity
                    weatherInfoBuilder.setHumidity(currentObservationResponse.getHumidity()
                            .floatValue());

                    ForecastResponse forecastResponse =
                            wundergroundReponse.getForecast();

                    if (forecastResponse == null) {
                        Log.d(TAG, "Null fc reponse, return");
                        serviceRequest.fail();
                        return;
                    }

                    SimpleForecastResponse simpleForecastResponse =
                            forecastResponse.getSimpleForecast();

                    if (simpleForecastResponse == null) {
                        Log.d(TAG, "Null sf reponse, return");
                        serviceRequest.fail();
                        return;
                    }

                    ArrayList<WeatherInfo.DayForecast> dayForecasts =
                            ConverterUtils.convertSimpleFCToDayForcast(
                                    simpleForecastResponse.getForecastDay());
                    weatherInfoBuilder.setForecast(dayForecasts);

                    ServiceRequestResult serviceRequestResult =
                            new ServiceRequestResult.Builder()
                            .setWeatherInfo(weatherInfoBuilder.build()).build();
                    serviceRequest.complete(serviceRequestResult);
                } else {
                    Log.d(TAG, "Response " + response.toString());
                }
            }

            @Override
            public void onFailure(Call<WundergroundReponse> call, Throwable t) {
                Log.d(TAG, "Failure " + t.toString());
                serviceRequest.fail();
            }
        });
    }

    //TODO IMPLEMENT
    private void processCityNameLookupRequest(final ServiceRequest serviceRequest) {
        final RequestInfo requestInfo = serviceRequest.getRequestInfo();
        Log.d(TAG, "Received city lookup request info: " + requestInfo.toString());


    }
}