package jp.ac.osaka_u.ist.sel.sairi;

import java.io.*;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.location.*;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;


public class OsakaUniversityBusGuide extends Activity implements BusInterface, LocationListener, OnClickListener {

	private double latitude, longitude;
	private LocationManager lm;
	private int from = 0;
	private Button btn01, btn02, btn03;
	private TimeTableManager tm;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Log.d("DEBUG ", "GO");

		tm = new TimeTableManager();

		btn01 = (Button) findViewById(R.id.Button01);
		btn01.setOnClickListener(this);
		btn02 = (Button) findViewById(R.id.Button02);
		btn02.setOnClickListener(this);
		btn03 = (Button) findViewById(R.id.Button03);
		btn03.setOnClickListener(this);

		lm = (LocationManager) getSystemService(LOCATION_SERVICE);
		if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
		if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
			lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
		if (!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) && !lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
			((TextView) findViewById(R.id.TextView06)).setText(getString(R.string.from) + getResources().getStringArray(R.array.busStop)[BUS_T]);

		// latitude= 34.823856;
		// longitude = 135.52383;

		((TextView) findViewById(R.id.TextView01)).setText(getString(R.string.search) + tm.getYMD() + " " + tm.getFormatedTime());
		Resources res = this.getResources();
		if (tm.isSuspension(res.openRawResource(SUS))) {
			((TextView) findViewById(R.id.TextView02)).setText(getString(R.string.suspension));
		}

		// busSearcher(td.getTime(),from);
	}


	private void busSearcher(int from) {
		Bus bus;
		switch (from) {
		case BUS_T: 
			bus = bus(BUS_T, BUS_SC);
			((TextView) findViewById(R.id.BusStop11)).setText(getResources().getStringArray(R.array.busStop)[BUS_T]);
			((TextView) findViewById(R.id.BusStop12)).setText(" >> " + getResources().getStringArray(R.array.busStop)[BUS_SC]);
			busTimeViewer((TextView) findViewById(R.id.BusTime1), (TextView) findViewById(R.id.BusGo1), (TextView) findViewById(R.id.Last1), bus);
			bus = bus(BUS_T, BUS_SE);
			((TextView) findViewById(R.id.BusStop21)).setText(getResources().getStringArray(R.array.busStop)[BUS_T]);
			((TextView) findViewById(R.id.BusStop22)).setText(" >> " + getResources().getStringArray(R.array.busStop)[BUS_SE]);
			busTimeViewer((TextView) findViewById(R.id.BusTime2), (TextView) findViewById(R.id.BusGo2), (TextView) findViewById(R.id.Last2), bus);
			break;
		case BUS_SH: 
			bus = bus(from, BUS_T);
			((TextView) findViewById(R.id.BusStop11)).setText(getResources().getStringArray(R.array.busStop)[BUS_SH]);
			((TextView) findViewById(R.id.BusStop12)).setText(" >> " + getResources().getStringArray(R.array.busStop)[BUS_T]);
			busTimeViewer((TextView) findViewById(R.id.BusTime1), (TextView) findViewById(R.id.BusGo1), (TextView) findViewById(R.id.Last1), bus);
			bus = bus(BUS_SE, BUS_T);
			((TextView) findViewById(R.id.BusStop21)).setText(getResources().getStringArray(R.array.busStop)[BUS_SE]);
			((TextView) findViewById(R.id.BusStop22)).setText(" >> " + getResources().getStringArray(R.array.busStop)[BUS_T]);
			busTimeViewer((TextView) findViewById(R.id.BusTime2), (TextView) findViewById(R.id.BusGo2), (TextView) findViewById(R.id.Last2), bus);
			break;
		case BUS_SE: 
			bus = bus(BUS_SE, BUS_T);
			((TextView) findViewById(R.id.BusStop11)).setText(getResources().getStringArray(R.array.busStop)[BUS_SE]);
			((TextView) findViewById(R.id.BusStop12)).setText(" >> " + getResources().getStringArray(R.array.busStop)[BUS_T]);
			busTimeViewer((TextView) findViewById(R.id.BusTime1), (TextView) findViewById(R.id.BusGo1), (TextView) findViewById(R.id.Last1), bus);
			bus = bus(BUS_SH, BUS_T);
			((TextView) findViewById(R.id.BusStop21)).setText(getResources().getStringArray(R.array.busStop)[BUS_SH]);
			((TextView) findViewById(R.id.BusStop22)).setText(" >> " + getResources().getStringArray(R.array.busStop)[BUS_T]);
			busTimeViewer((TextView) findViewById(R.id.BusTime2), (TextView) findViewById(R.id.BusGo2), (TextView) findViewById(R.id.Last2), bus);
			break;
		}
	}


	private void busTimeViewer(TextView v1, TextView v2, TextView v3, Bus bus) {
		if (bus == null) {
			v1.setText(getString(R.string.end));
			v2.setText("");
			v3.setText("");
		} else {
			v1.setText(formatTime(bus.getFromTime()) + " >> " + formatTime(bus.getToTime()));
			v2.setText(getResources().getStringArray(R.array.busGo)[bus.busGo()]);
			v3.setText((bus.isLastBus()) ? getString(R.string.last) : "");
		}
	}

	public Bus bus(int from, int to) {

		return tm.bus(from, to, goodIs(from, to));
	}

	private InputStream goodIs(int from, int to) {

		Resources res = this.getResources();
		if (from < to) {
			return res.openRawResource(TT1);

		} else {
			return res.openRawResource(TT2);
		}

	}

	private int whereAmI(double latitude, double longitude) {
		if (latitude > 34.836 && longitude + latitude > 170.325)
			return BUS_M;
		else if (longitude < 135.489 && longitude + latitude < 170.325)
			return BUS_T;
		else if (longitude - latitude < 100.703)
			return BUS_SE;
		else
			return BUS_SH;
	}

	@Override
	public void onLocationChanged(Location location) {
		latitude = location.getLatitude();
		longitude = location.getLongitude();
		from = whereAmI(latitude, longitude);
		((TextView) findViewById(R.id.TextView06)).setText(getString(R.string.now) + getResources().getStringArray(R.array.busStop)[from]);
		busSearcher(from);
		stopLM();
	}

	@Override
	public void onProviderDisabled(String provider) {
	}

	@Override
	public void onProviderEnabled(String provider) {
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
	}

	private void stopLM() {
		lm.removeUpdates(this);
	}

	@Override
	public void onClick(View v) {
		if (v == btn01) {
			new AlertDialog.Builder(this).setTitle(R.string.button01).setItems(R.array.campus, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialoginterface, int i) {
					from = i * 2;
					stopLM();
					((TextView) findViewById(R.id.TextView06)).setText(getString(R.string.from) + getResources().getStringArray(R.array.campus)[i]);
					busSearcher(from);
				}
			}).show();

		} else if (v == btn02) {
			new TimePickerDialog(OsakaUniversityBusGuide.this, new TimePickerDialog.OnTimeSetListener() {
				public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
					tm.setTime(hourOfDay * 100 + minute);
					stopLM();
					((TextView) findViewById(R.id.TextView06)).setText(getString(R.string.from) + getResources().getStringArray(R.array.campus)[from / 2]);
					busSearcher(from);
					((TextView) findViewById(R.id.TextView01)).setText(getString(R.string.search) + tm.getYMD() + " " + tm.getFormatedTime());
				}
			}, tm.getTime() / 100, tm.getTime() % 100, true).show();
		} else if (v == btn03) {
			// timetable
			Intent intent = new Intent(this, jp.ac.osaka_u.ist.sel.sairi.TimeTableActivity.class);
			intent.putExtra("from", from);
			startActivity(intent);
		}
	}

	public String formatTime(int time) {
		return (String.format("%1$02d", time / 100) + ":" + String.format("%1$02d", time % 100));
	}

	public static boolean isConnected(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni != null) {
			return cm.getActiveNetworkInfo().isConnected();
		}
		return false;
	}
}