package com.cc.infosur.map;

import java.util.List;

import org.osmdroid.api.IGeoPoint;
import org.osmdroid.util.GeoPoint;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.os.AsyncTask;

import com.cc.infosur.db.TestAdapter;
import com.cc.infosur.main.LoadRoutingTask;
import com.cc.infosur.main.MainActivity;
import com.cc.infosur.routing.Network;


/**
 * Class RoutingAsyncTask
 */
public class RoutingAsyncTask extends AsyncTask<Void, Void, Boolean> {

	private Context context;
	private Network network;
	private GeoPoint source;
	private GeoPoint destination;

	/**
	 * Constructor
	 * @param context
	 * @param network
	 * @param source
	 * @param destination
	 */
	public RoutingAsyncTask(Context context, Network network, GeoPoint source, GeoPoint destination) {
		super();
		this.context = context;
		this.network = network;
		this.source = source;
		this.destination = destination;
	}


	/**
	 * Function onPreExecute() - AsyncTask 1 / 3
	 */
	ProgressDialog pDialog;
	protected void onPreExecute() {
		pDialog = new ProgressDialog(context);
		pDialog.setMessage("Calculate routing...");
		pDialog.setCancelable(false);
		pDialog.setCanceledOnTouchOutside(false);
		pDialog.show();
	}


	/**
	 * Function doInBackground() - AsyncTask 2 / 3
	 * @param params
	 * @return
	 */
	@Override
	protected Boolean doInBackground(Void... params) {

		try {

			final List<IGeoPoint> points = network.calculateRoute(
					source.getLatitude(),
					source.getLongitude(),
					destination.getLatitude(),
					destination.getLongitude());
			if (points.size()==0)
				return false;
			((Activity) context).runOnUiThread(new Runnable() {
				@Override
				public void run() {
					MapFragment.drawPath(points);
				}
			});

		} catch(Exception e) {

			TestAdapter mDbHelper = new TestAdapter(context, "routingdb");
			mDbHelper.createDatabase(""+ MainActivity.getEtpParkId(), "routingdb");
			mDbHelper.close();
			return false;

		}

		return true;

	}


	/**
	 * Function onPostExecute() - AsyncTask 3 / 3
	 * @param result
	 */
	protected void onPostExecute(Boolean result) {

		pDialog.dismiss();

		if (!result) {

			new AlertDialog.Builder(context)
					.setTitle("Route not available")
					.setPositiveButton("Download roads",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {

									// Allow the user to download the roads as his wish
									ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
									boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();

									if(isWifi) {
										dialog.dismiss();
										new LoadRoutingTask(context).execute();
									} else {
										dialog.dismiss();
										showNoInternetDialog();
									}
								}
							})
					.setNegativeButton("Dismiss",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
								}
							}).show();
		} else {
			// Nothing
		}
	}


	/**
	 * Function showNoInternetDialog
	 *
	 * Dialog message to warn the traveler that the WiFi is required to download the roads
	 */
	public void showNoInternetDialog() {

		new AlertDialog.Builder(context)
				.setTitle("No Internet")
				.setMessage("Please enable the WIFI or the 3G. The connection is required to download the roads.")
				.setNegativeButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						}).show();

	}


}