aboutsummaryrefslogtreecommitdiff
path: root/src/net/cbaines/suma/BusStopActivity.java
blob: bfcc13a365f4564306d965c7ffffe0a426c9d255 (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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
/*
 * Southampton University Map App
 * Copyright (C) 2011  Christopher Baines
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package net.cbaines.suma;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;

public class BusStopActivity extends OrmLiteBaseActivity<DatabaseHelper> implements OnCheckedChangeListener, Preferences,
		OnItemClickListener, OnLongClickListener {

	final static String TAG = "BusTimeActivity";

	private ListView busTimeList;
	private TextView busName;
	private TextView busID;
	private CheckBox busFavourite;
	private TextView busStopMessage;
	private ProgressBar progBar;
	private LinearLayout busTimeContentLayout;

	protected Timetable timetable;
	private Timetable visibleTimetable;

	private BusStop busStop;

	private GetTimetableTask timetableTask;

	private Context instance;

	private Handler mHandler;
	private Runnable refreshData;

	private CheckBox U1RouteRadioButton;
	private CheckBox U1NRouteRadioButton;
	private CheckBox U2RouteRadioButton;
	private CheckBox U6RouteRadioButton;
	private CheckBox U9RouteRadioButton;

	private static final int POI_DIALOG_ID = 0;
	private POIDialog busDialog;

	private HashSet<BusRoute> routes = new HashSet<BusRoute>();

	Toast activityToast;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bus_stop_activity);

		Log.i(TAG, "getIntent().getDataString() " + getIntent().getDataString());

		String busStopID;

		if (getIntent().getDataString().startsWith("http://data")) {

			String[] uriParts = getIntent().getDataString().split("/");

			busStopID = uriParts[uriParts.length - 1].replace(".html", "");

		} else {

			String[] uriParts = getIntent().getDataString().split("/");

			busStopID = uriParts[uriParts.length - 1];
		}

		final DatabaseHelper helper = getHelper();

		SharedPreferences favouritesPreferences = getSharedPreferences(FAVOURITES_PREFERENCES, 0);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

		instance = this;

		U1RouteRadioButton = (CheckBox) findViewById(R.id.radio_u1);
		U1NRouteRadioButton = (CheckBox) findViewById(R.id.radio_u1n);
		U2RouteRadioButton = (CheckBox) findViewById(R.id.radio_u2);
		U6RouteRadioButton = (CheckBox) findViewById(R.id.radio_u6);
		U9RouteRadioButton = (CheckBox) findViewById(R.id.radio_u9);

		U1RouteRadioButton.setOnCheckedChangeListener(this);
		U1RouteRadioButton.setOnLongClickListener(this);

		U1NRouteRadioButton.setOnCheckedChangeListener(this);
		U1NRouteRadioButton.setOnLongClickListener(this);

		U2RouteRadioButton.setOnCheckedChangeListener(this);
		U2RouteRadioButton.setOnLongClickListener(this);

		U6RouteRadioButton.setOnCheckedChangeListener(this);
		U6RouteRadioButton.setOnLongClickListener(this);

		U9RouteRadioButton.setOnCheckedChangeListener(this);
		U9RouteRadioButton.setOnLongClickListener(this);

		try {
			Dao<BusStop, String> busStopDao = helper.getBusStopDao();

			busStop = busStopDao.queryForId(busStopID);

			Dao<BusRoute, Integer> busRouteDao = helper.getBusRouteDao();
			Dao<RouteStop, Integer> routeStopsDao = helper.getRouteStopsDao();

			for (BusRoute route : busRouteDao) {
				QueryBuilder<RouteStop, Integer> queryBuilder = routeStopsDao.queryBuilder();

				queryBuilder.where().eq(RouteStop.ROUTE_ID_FIELD_NAME, route.id).and()
						.eq(RouteStop.STOP_ID_FIELD_NAME, busStopID);
				queryBuilder.setCountOf(true);
				PreparedQuery<RouteStop> preparedQuery = queryBuilder.prepare();

				long count = routeStopsDao.countOf(preparedQuery);

				if (route.code.equals("U1")) {
					if (count != 0) {
						U1RouteRadioButton.setVisibility(View.VISIBLE);
						routes.add(route);
					} else {
						U1RouteRadioButton.setVisibility(View.GONE);
					}
				} else if (route.code.equals("U1N")) {
					if (count != 0) {
						U1NRouteRadioButton.setVisibility(View.VISIBLE);
						routes.add(route);
					} else {
						U1NRouteRadioButton.setVisibility(View.GONE);
					}
				} else if (route.code.equals("U2")) {
					if (count != 0) {
						U2RouteRadioButton.setVisibility(View.VISIBLE);
						routes.add(route);
					} else {
						U2RouteRadioButton.setVisibility(View.GONE);
					}
				} else if (route.code.equals("U6")) {
					if (count != 0) {
						U6RouteRadioButton.setVisibility(View.VISIBLE);
						routes.add(route);
					} else {
						U6RouteRadioButton.setVisibility(View.GONE);
					}
				} else if (route.code.equals("U9")) {
					if (count != 0) {
						U9RouteRadioButton.setVisibility(View.VISIBLE);
						routes.add(route);
					} else {
						U9RouteRadioButton.setVisibility(View.GONE);
					}
				}
			}

			busFavourite = (CheckBox) findViewById(R.id.favouriteCheckBox);
			busFavourite.setChecked(favouritesPreferences.getBoolean(busStop.id, false));
			busFavourite.setOnCheckedChangeListener(this);

		} catch (SQLException e) {
			e.printStackTrace();
		}

		busName = (TextView) findViewById(R.id.busStopName);

		if (prefs.getBoolean(SHOW_IDENTIFIERS, SHOW_IDENTIFIERS_ENABLED_BY_DEFAULT)) {
			busID = (TextView) findViewById(R.id.busStopID);
			busID.setText(busStopID);
			busID.setVisibility(View.VISIBLE);
		}

		busStopMessage = (TextView) findViewById(R.id.busStopMessage);
		progBar = (ProgressBar) findViewById(R.id.busStopLoadBar);
		busTimeList = (ListView) findViewById(R.id.busStopTimes);
		busTimeContentLayout = (LinearLayout) findViewById(R.id.busTimeContentLayout);

		Log.i(TAG, "Got busstop id " + busStopID);

		busName.setText(busStop.description);
	}

	public void onResume() {
		super.onResume();

		SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
		if (sharedPrefs.getBoolean(UNI_LINK_BUS_TIMES, UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT)
				|| sharedPrefs.getBoolean(NON_UNI_LINK_BUS_TIMES, NON_UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT)) {
			Log.i(TAG, "Live Times enabled");
			timetable = (Timetable) getLastNonConfigurationInstance();

			refreshData = new Runnable() {
				public void run() {
					timetableTask = new GetTimetableTask();
					timetableTask.execute(busStop.id);
					mHandler.postDelayed(refreshData, 20000);
				}
			};

			mHandler = new Handler();

			if (timetable == null) {
				Log.i(TAG, "No Previous timetable");
				mHandler.post(refreshData);
			} else {
				Log.i(TAG, "Displaying previous timetable");
				displayTimetable(timetable);
				if (System.currentTimeMillis() - timetable.fetchTime.getTime() > 20000) {
					mHandler.post(refreshData);
				}
			}

		} else {
			Log.i(TAG, "Live Times Disabled");
			progBar.setVisibility(View.GONE);
			busStopMessage.setText("Live bus times disabled");
			busStopMessage.setVisibility(View.VISIBLE);
		}

	}

	public void onPause() {
		if (mHandler != null) { // BusTimes are enabled
			mHandler.removeCallbacks(refreshData);
			if (timetableTask != null) // Could happen if the handler has not
										// created the timetableTask yet
				timetableTask.cancel(true);
			Log.i(TAG, "Stoping refreshing timetable data");
		}

		super.onPause();
	}

	public void finish() {
		setResult(RESULT_OK, getIntent());
		super.finish();
	}

	public void onCheckedChanged(CompoundButton button, boolean checked) {
		if (button.equals(busFavourite)) {
			SharedPreferences favouritesPreferences = getSharedPreferences(FAVOURITES_PREFERENCES, 0);

			if (checked) {
				favouritesPreferences.edit().putBoolean(busStop.id, true).commit();
			} else {
				favouritesPreferences.edit().remove(busStop.id).commit();
			}
		} else {
			Log.i(TAG, "Route radio button made " + checked);
			if (timetable != null) { // If there is a timetable to display
				displayTimetable(timetable);
			}
		}
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		return timetable;
	}

	private class GetTimetableTask extends AsyncTask<String, Integer, Timetable> {
		String errorMessage;

		protected void onPreExecute() {
			progBar.setVisibility(View.VISIBLE);
		}

		protected Timetable doInBackground(String... activity) {
			Timetable newTimetable = null;
			try {
				final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(instance);

				newTimetable = DataManager
						.getTimetable(instance, busStop.id, sharedPrefs.getBoolean(MapActivity.UNI_LINK_BUS_TIMES,
								MapActivity.UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT), sharedPrefs.getBoolean(
								MapActivity.NON_UNI_LINK_BUS_TIMES, MapActivity.NON_UNI_LINK_BUS_TIMES_ENABLED_BY_DEFAULT));
			} catch (SQLException e) {
				errorMessage = "Error message regarding SQL?";
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				errorMessage = "ClientProtocolException!?!";
				e.printStackTrace();
			} catch (IOException e) {
				errorMessage = "Error fetching bus times from server, are you connected to the internet?";
				e.printStackTrace();
			} catch (JSONException e) {
				errorMessage = "Error parsing bus times";
				e.printStackTrace();
			} catch (Exception e) {
				Log.e(TAG, e.getMessage(), e.getCause());
			}

			return newTimetable;
		}

		protected void onPostExecute(Timetable newTimetable) {
			Log.i(TAG, "Got timetable for " + busStop.id);
			if (newTimetable == null) {
				Log.i(TAG, "Its null");

				progBar.setVisibility(View.GONE);
				busStopMessage.setText(errorMessage);
				busStopMessage.setVisibility(View.VISIBLE);
			} else {
				progBar.setVisibility(View.GONE);
				timetable = newTimetable;
				displayTimetable(timetable);
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.stop_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		if (item.getItemId() == R.id.menu_previous_stop || item.getItemId() == R.id.menu_next_stop) {
			Log.v(TAG, "Got a request for the stop movement");

			Log.v(TAG, routes.size() + " routes avalible from this stop");

			ArrayList<POI> busStops = new ArrayList<POI>();

			for (BusRoute route : routes) {
				try {
					Set<BusStop> tmpStops;
					if (item.getItemId() == R.id.menu_next_stop) {
						tmpStops = route.moveInRoute(this, getHelper().getBusStopDao().queryForId(busStop.id), 1);
					} else {
						tmpStops = route.moveInRoute(this, getHelper().getBusStopDao().queryForId(busStop.id), -1);
					}
					for (BusStop busStop : tmpStops) {
						if (!busStops.contains(busStop)) {
							busStops.add(busStop);
						}
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			Log.i(TAG, "stops " + busStops);

			if (busStops.size() == 1) {

				BusStop stop = (BusStop) busStops.iterator().next();
				if (stop == null) {
					Log.e(TAG, "stop == null");
				}
				if (stop.id == null) {
					Log.e(TAG, "stop.id == null");
				}

				Uri uri = Uri.parse("http://id.southampton.ac.uk/bus-stop/" + busStop.id);

				Log.i(TAG, "Starting a activity for " + uri + " path " + uri.getPath());

				Intent busStopIntent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(busStopIntent);

			} else {
				showDialog(POI_DIALOG_ID);
				if (busDialog == null) {
					Log.e(TAG, "Very wierd, just tried to launch the favourite's dialog, but its null?");
					return false;
				}

				busDialog.setMessage("");
				busDialog.setItems(busStops);
				busDialog.setTitle("Choose Bus Stop");

				Log.i(TAG, "Showing dialog");
			}

		} else if (item.getItemId() == R.id.menu_refresh_stop) {
			if (mHandler != null) { // BusTimes are enabled
				mHandler.removeCallbacks(refreshData);
				timetableTask.cancel(true);
				Log.i(TAG, "Stoping refreshing timetable data");

				mHandler.post(refreshData);
			} else {
				// TODO: Toast here...
			}
		} else {
			Log.e(TAG, "No known menu option selected");
			return super.onOptionsItemSelected(item);
		}
		return true;
	}

	private void displayTimetable(Timetable timetable) {
		visibleTimetable = (Timetable) timetable.clone();

		Log.i(TAG, "It contains " + visibleTimetable.size() + " stops");

		if (timetable.size() == 0) {
			busStopMessage.setText("No Busses");
			busStopMessage.setVisibility(View.VISIBLE);
			busTimeContentLayout.setGravity(Gravity.CENTER);
		} else {

			for (Iterator<Stop> stopIter = visibleTimetable.iterator(); stopIter.hasNext();) {
				Stop stop = stopIter.next();
				Log.i(TAG, "Begin filtering, looking at " + stop + " with route " + stop.bus.route.code);
				if (stop.bus.route.code.equals("U1")) {
					if (!U1RouteRadioButton.isChecked()) {
						stopIter.remove();
					}
				} else if (stop.bus.route.code.equals("U1N")) {
					if (!U1NRouteRadioButton.isChecked()) {
						stopIter.remove();
					}
				} else if (stop.bus.route.code.equals("U2")) {
					if (!U2RouteRadioButton.isChecked()) {
						stopIter.remove();
					}
				} else if (stop.bus.route.code.equals("U6")) {
					if (!U6RouteRadioButton.isChecked()) {
						stopIter.remove();
					}
				} else if (stop.bus.route.code.equals("U9")) {
					if (!U9RouteRadioButton.isChecked()) {
						stopIter.remove();
					}
				}
			}

			if (visibleTimetable.size() == 0) {
				busTimeContentLayout.setGravity(Gravity.CENTER);
				busStopMessage.setText("No Busses (With the current enabled routes)");
				busStopMessage.setVisibility(View.VISIBLE);
				busTimeList.setVisibility(View.GONE);
			} else {
				busTimeList.setVisibility(View.VISIBLE);
				busStopMessage.setVisibility(View.GONE);
				TimetableAdapter adapter;
				if ((adapter = (TimetableAdapter) busTimeList.getAdapter()) != null) {
					adapter.updateTimetable(visibleTimetable);
				} else {
					adapter = new TimetableAdapter(this, visibleTimetable);
					busTimeList.setAdapter(adapter);
				}
				busTimeContentLayout.setGravity(Gravity.TOP);
			}
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case POI_DIALOG_ID:
			busDialog = new POIDialog(instance);
			busDialog.setOnItemClickListener(this);
			return busDialog;
		}
		return null;
	}

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Log.i(TAG, "OnItemClick pos " + position + " id " + id);

		String busId = busDialog.adapter.getItemStringId(position);

		Log.i(TAG, "Bus " + busId + " selected");

		Uri uri = Uri.parse("http://id.southampton.ac.uk/bus/" + busId);

		Log.i(TAG, "Starting a activity for " + uri + " path " + uri.getPath());

		Intent busStopIntent = new Intent(Intent.ACTION_VIEW, uri);
		busStopIntent.putExtra("busStopID", busStop.id);
		startActivity(busStopIntent);
	}

	public boolean onLongClick(View v) {
		Uri uri = null;
		if (v.equals(U1RouteRadioButton)) {
			uri = Uri.parse("http://id.southampton.ac.uk/bus-route/326");
		} else if (v.equals(U1NRouteRadioButton)) {
			uri = Uri.parse("http://id.southampton.ac.uk/bus-route/468");
		} else if (v.equals(U2RouteRadioButton)) {
			uri = Uri.parse("http://id.southampton.ac.uk/bus-route/329");
		} else if (v.equals(U6RouteRadioButton)) {
			uri = Uri.parse("http://id.southampton.ac.uk/bus-route/327");
		} else if (v.equals(U9RouteRadioButton)) {
			uri = Uri.parse("http://id.southampton.ac.uk/bus-route/354");
		}
		if (uri != null) {
			Log.i(TAG, "Starting a activity for " + uri + " path " + uri.getPath());

			Intent busStopIntent = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(busStopIntent);
		}
		return false;
	}
}