/*
 * LoadActivity.java
 * First activity of the application
 * Checks the user credentials and loads the trip list activity
 */

package com.cc.infosur.main;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.sqlite.SQLiteDatabase;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.cc.infosur.greendao.DaoMaster;
import com.cc.infosur.greendao.DaoMaster.DevOpenHelper;
import com.cc.infosur.greendao.DaoSession;
import com.cc.infosur.greendao.Link;
import com.cc.infosur.greendao.LinkDao;
import com.cc.infosur.greendao.Node;
import com.cc.infosur.greendao.NodeDao;
import com.cc.infosur.greendao.TravellerInfo;
import com.cc.infosur.greendao.TravellerInfoDao;
import com.cc.infosur.greendao.TripDao;
import com.cc.infosur.greendao.TripInfoDao;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.cc.infosur.R;

public class LoadActivity extends Activity {
	
	private Context context;
	//private EditText emailInput = null;
	//private EditText passwordInput = null;
	String email = "";
	String password = "";
	
	// Database variables
	private SQLiteDatabase db;
	private DevOpenHelper helper;
	private DaoSession daoSession;
	private DaoMaster daoMaster;
	private TravellerInfoDao travellerInfoDao;
	private TripInfoDao tripInfoDao;
    private TripDao tripDao;

    private LocationManager locationManager;
    private TripListActivity tripListActivity;


	@Override
	public void onBackPressed() {
		// EXIT THE APPLICATION
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
		System.exit(1);
    }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_load);

		//context = LoadActivity.this;
		
		// Reference to actionbar
		ActionBar abar = getActionBar();
		abar.hide();
		
		// Block orientation if mobile
		if (!MainActivity.isTablet(this))
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		// Load buttons from layout
		ImageView submitButton = (ImageView) findViewById(R.id.buttonSubmit);
		Button routingButton = (Button) findViewById(R.id.buttonLoadRouting);

		// Demo trip
		LinearLayout demoTripLayout = (LinearLayout) findViewById(R.id.demoTripLayout);
		demoTripLayout.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				loadDemoTrip();
			}
		});

		
		email = "infouser@gmail1.com";
		password = "12345678";


        /*emailInput.setText("farid@gmail5.com");//user_Rock7 : cu13580   (farid)
        passwordInput.setText("12345678");
		emailInput.setText("infouser@gmail1.com");//user_Rock7 : cu13580   (farid)
		passwordInput.setText("12345678");*/


		submitButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {


                ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

                boolean is3g = false;
                // Mobile
                try {
                    is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();

                } catch (Exception e) {
                    is3g = false;
                    e.printStackTrace();
                }
                // Wifi
                boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();



                String emailValue = "";
                String passwordValue = "";

                try {
                    // Variables
                    emailValue = email;
                    passwordValue = md5(password);
                } catch (Exception e) {
                    e.printStackTrace();
                }

				// If there is not 3G or Wifi : Display an error message
				if(!is3g && !isWifi) {

                    helper = new DaoMaster.DevOpenHelper(LoadActivity.this, "tripdb", null);
                    db = helper.getWritableDatabase();
                    daoMaster = new DaoMaster(db);
                    daoSession = daoMaster.newSession();
                    travellerInfoDao = daoSession.getTravellerInfoDao();
                    tripDao = daoSession.getTripDao();


                    // If there is travellerInfo (user / traveler) & trip Data on the GreenDao DATABASE
                    // This case is for the part if the mobile application has crashed, the login required the WIFI, but if the data are there, stored in the Database (Greendao), then he'll still be able to connect
                    if(travellerInfoDao.loadAll().size() > 0 && tripDao.loadAll().size() > 0) {

                        // Variables
                        String emailDB = travellerInfoDao.loadAll().get(0).getEmail().toString();
                        String passwordDB = travellerInfoDao.loadAll().get(0).getPassword().toString();

                        // Remove empty spaces
                        emailValue = emailValue.replaceAll("\\s+$", "");
                        passwordValue = passwordValue.replaceAll("\\s+$", "");
                        emailDB = emailDB.replaceAll("\\s+$", "");
                        passwordDB = passwordDB.replaceAll("\\s+$", "");

                        if(emailValue.matches("") || passwordValue.matches("")) {

                            // Empty fields
                            showEmptyFields();

                        // Check if it's the right account
                        } else if( emailValue.equals(emailDB) && passwordValue.equals(passwordDB) ) {

                            // Display the previous trip already downloaded
                            Intent intent = new Intent(LoadActivity.this, MainActivity.class);
                            startActivity(intent);

                        // Wrong email or password
                        } else showWrongAccount();


                    // No Internet enabled
                    } else showNoInternetDialog();


				} else {

                // Empty Fields
                    if(emailValue.matches("") || passwordValue.matches("")) showEmptyFields();

					// Check the audio status, if it's in mode Silent or Vibrate : put the mode Normal (with Sound)
					/*AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

					switch (am.getRingerMode()) {
					    case AudioManager.RINGER_MODE_SILENT:
					        am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
					        break;
					    case AudioManager.RINGER_MODE_VIBRATE:
					        am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
					        break;
					    case AudioManager.RINGER_MODE_NORMAL:
					        break;
					}*/
					new LoadRoutingTask(LoadActivity.this).execute();


				}
				
			}
		});

		/*routingButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

                System.out.println(" ROUTING PRESS ");


                ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

                boolean is3g = false;
                // Mobile
                try {
                    is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();

                } catch (Exception e) {
                    is3g = false;
                    e.printStackTrace();
                }
                // Wifi
                boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();


                LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                Criteria criteria = new Criteria();
                String provider = lm.getBestProvider(criteria, true);

                String providertest = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
                if(!providertest.equals("")) {
                    System.out.println(" GPS ENABLED ");
                } else {
                    System.out.println(" GPS NOT ENABLED ");
                    showGpsDialog();
                }

                // If there is not 3G or Wifi : Display an error message
                if(!is3g && !isWifi) {

                     showNoInternetDialog();

                // Load Routing
                } else {

                    new LoadRoutingTask(LoadActivity.this).execute();

                }

			}
		});*/

	}



    /**
     * Function DateToCalendar
     * @param date
     * @return
     */
	private Calendar DateToCalendar(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		return cal;
	}



    /**
     * Function md5
     * @param input
     * @return
     */
    public String md5(String input) throws NoSuchAlgorithmException {
        String result = input;
        if(input != null) {
            MessageDigest md = MessageDigest.getInstance("MD5"); //or "SHA-1"
            md.update(input.getBytes());
            BigInteger hash = new BigInteger(1, md.digest());
            result = hash.toString(16);
            while(result.length() < 32) { //40 for SHA-1
                result = "0" + result;
            }
        }
        return result;
    }



    /**
     * Function launchGPSOptions
     */
    private void launchGPSOptions() {
        final ComponentName toLaunch = new ComponentName("com.android.settings","com.android.settings.SecuritySettings");
        final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setComponent(toLaunch);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, 0);
    }



    /**
     * Function showEmptyFields
     */
    public void showEmptyFields() {

        new AlertDialog.Builder(LoadActivity.this)
                .setTitle(context.getResources().getString(R.string.missing_field))
                .setMessage(context.getResources().getString(R.string.fill_field))
                .setNegativeButton("Ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();

    }



    /**
     * Function showWrongAccount
     */
    public void showWrongAccount() {

        new AlertDialog.Builder(LoadActivity.this)
                .setTitle(context.getResources().getString(R.string.connexion_error))
                .setMessage(context.getResources().getString(R.string.bad_pseudo_password))
                .setNegativeButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();

    }



    /**
     * Function showNoInternetDialog
     */
    public void showNoInternetDialog() {

        new AlertDialog.Builder(LoadActivity.this)
                .setTitle(this.getResources().getString(R.string.connexion_error))
                .setMessage(this.getResources().getString(R.string.check_connexion))
                .setNegativeButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();

    }



    public static boolean isGpsEnabled (Context context) {

        //if(Build.VERSION.SDK_INT < )

        return false;
    }



    /**
     * Function showGpsDialog()
     */
    public void showGpsDialog() {

        new AlertDialog.Builder(LoadActivity.this)
                .setTitle("GPS not available")
                .setMessage("Your GPS seems to be disabled, do you want to enable it ?")
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            }
                        })
                .setNegativeButton("No",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                            }
                        }).show();

    }


    /**
     * Function convertStreamToString()
     * @param is
     * @return
     */
	private static String convertStreamToString(InputStream is) {

		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF8"));

            // System.gc();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.load, menu);
		return true;
	}

	public String getEmail() {
		return email;
	}


	public String getPassword() {
		return password;
	}

    /**
     * Function showTrips()
     * @param travellerId
     *
     * Pass data to the TripList Activity and loads it
     */
	public void showTrips(Integer travellerId) {
		Intent intent = new Intent(LoadActivity.this, TripListActivity.class);
		Bundle bundle = new Bundle();
		bundle.putInt("travellerId", travellerId);
		intent.putExtras(bundle);
		startActivity(intent);
	}



    /**
     * Function loadDemoTrip()
     *
     * Sets some variables in the database to load the demo trip
     */
	private void loadDemoTrip() {

		// Prepare db
		helper = new DaoMaster.DevOpenHelper(this, "tripdb", null);
		db = helper.getWritableDatabase();
		daoMaster = new DaoMaster(db);
		daoSession = daoMaster.newSession();
		travellerInfoDao = daoSession.getTravellerInfoDao();
		tripInfoDao = daoSession.getTripInfoDao();
		
		// Delete
		travellerInfoDao.deleteAll();
		tripInfoDao.deleteAll();
		
		TravellerInfo travellerInfo = new TravellerInfo();
		travellerInfo.setId(0L);
		
		travellerInfoDao.insert(travellerInfo);
		
		showTrips(0);
	}


	
	/*
	 * LoadRouting and DownloadMaps tasks
	 * Unfinished functions, maybe not needed in the future
	 */


    /** !!!!!!!!!!!!!!!!!!!!!!!!!! **/

    /** STEVEN : NOT USED ANYMORE **/

    /** Replace by : Main/LoadRoutingTask.java **/


    /**
     * Class LoadRoutingTask
     */
	public class LoadRoutingTask extends AsyncTask<Void, Void, Boolean> {
		private SQLiteDatabase db;
		private DevOpenHelper helper;
		private DaoSession daoSession;
		private DaoMaster daoMaster;
		private NodeDao nodeDao;
		private LinkDao linkDao;


		private Context context;
		List<Double> nodeLatitudes = new ArrayList<Double>();
		List<Double> nodeLongitudes = new ArrayList<Double>();

        // Long linkId = 1L;
		Long nodeId = 0L;

		private String convertStreamToString(InputStream is) {

			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			StringBuilder sb = new StringBuilder();

			String line = null;
			try {
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return sb.toString();
		}

		private Node addNode(Double latitude, Double longitude, Boolean mainNode, Long linkForward, int positionForward, Long linkBackward, int positionBackward) {

            if (mainNode) {

				if (latitude == -26.180895000437406 && longitude == 20.8199594441027) {
					Log.i("PATH", "NODE FOUND");
				}

				for (int i = 0; i < nodeLatitudes.size(); i++) {
					if (nodeLatitudes.get(i).equals(latitude)
							&& nodeLongitudes.get(i).equals(longitude)) {
						if (latitude == -26.180895000437406
								&& longitude == 20.8199594441027) {
							Log.i("PATH", "NODE REPEAT " + i);
						}
						return nodeDao.load((long) i);
					}
				}
				// List<Node> nodes = nodeDao
				// .queryBuilder()
				// .where(Properties.Longitude.eq(longitude),
				// Properties.Latitude.eq(latitude)).list();
				// if (nodes.size() > 0) {
				// if (latitude == -26.180895000437406 && longitude ==
				// 20.8199594441027){
				// Log.i("PATH", "NODE REPEAT");
				// }
				// return nodes.get(0);
				// }
			}
			Node node = new Node();
			node.setId(nodeId++);
			nodeLatitudes.add(latitude);
			nodeLongitudes.add(longitude);
			node.setLatitude(latitude);
			node.setLongitude(longitude);
			node.setLinkForward(linkForward);
			node.setPositionForward(positionForward);
			node.setLinkBackward(linkBackward);
			node.setPositionBackward(positionBackward);
			// Log.i("JSON", "Node to insert: " + node.getId() + " " +
			// node.getLatitude() + " " + node.getLongitude());
			nodeDao.insert(node);
			if (latitude == -26.180895000437406 && longitude == 20.8199594441027) {
				Log.i("PATH","NODE: " + node.getId() + " - " + node.getLatitude()+ "," + node.getLongitude());
			}
			return node;
		}

		public LoadRoutingTask(LoadActivity activity) {
			super();
			context = activity;
		}


        ProgressDialog pDialog;

		protected void onPreExecute() {
			pDialog = new ProgressDialog(context);
            pDialog.setTitle(context.getResources().getString(R.string.download));
			pDialog.setMessage(context.getResources().getString(R.string.download_routing));
            pDialog.setProgressStyle(pDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(false);
			pDialog.setCanceledOnTouchOutside(false);
			pDialog.show();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			String jsonStr = null;

            System.out.println(" ++ SENSA ++ :: LoadActivity :: ");
			// Create a new HttpClient and Post Header
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
			        // "http://144.76.175.87:8080/geoserver/sensa/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=sensa:roads&outputFormat=json&srsName=EPSG:4326&Filter=%3CFilter%3E%3COr%3E%3CPropertyIsEqualTo%3E%3CPropertyName%3EClass%3C/PropertyName%3E%3CLiteral%3EMain%3C/Literal%3E%3C/PropertyIsEqualTo%3E%3CPropertyIsEqualTo%3E%3CPropertyName%3EClass%3C/PropertyName%3E%3CLiteral%3ESecondary%3C/Literal%3E%3C/PropertyIsEqualTo%3E%3C/Or%3E%3C/Filter%3E");
                    // "http://10.112.10.134/maps/kgalagadi_gaborone.json"
                    // "http://10.112.10.134/road_network.json"
                    // "http://10.112.10.134/maps/map_gaborone.json"
                    // "http://10.112.10.134/roads.json"
                    // "http://10.112.10.134/maps/kgalagadi_roads_final.geojson"
                    // "http://sensa-demo.tripalacarte.com/frontend/json/kgalagadi_roads_final.geojson"
					///"http://sensa-demo.tripalacarte.com/frontend/json/pnpg_roads_complete.json"
                     "http://sensa-prod3.tripalacarte.com/frontend/json/eschsursure.json"
                    // "http://sensa-demo.tripalacarte.com/frontend/json/eschalzette.json"
					);
			try {

                System.out.println(" ++ SENSA ++ :: LoadActivity :: httppost :: " + httppost);

				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);

				// Get the string
				HttpEntity entity = response.getEntity();

				if (entity != null) {

					// A Simple JSON Response Read
					InputStream instream = entity.getContent();
					jsonStr = convertStreamToString(instream);
					// now you have the string representation of the HTML
					// request
					instream.close();
				}

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}

			// Prepare db
            helper = new DaoMaster.DevOpenHelper(context, "tripdb", null);
            db = helper.getWritableDatabase();
			daoMaster = new DaoMaster(db);
			daoSession = daoMaster.newSession();
			nodeDao = daoSession.getNodeDao();
			linkDao = daoSession.getLinkDao();

			// Delete before load
			nodeDao.deleteAll();
			linkDao.deleteAll();
			// nodeId = nodeDao.count();

			try {
				JSONObject networkObject = new JSONObject(jsonStr);

				JSONArray features = networkObject.getJSONArray("features");

                // Progress Dialog - Length Array
                pDialog.setMax(features.length());

				for (int i = 0; i < features.length(); i++) {

					JSONObject feature = features.getJSONObject(i);
					JSONObject properties = feature.getJSONObject("properties");
					// if (!properties.getString("Class").equals("Main"))
					// continue;
					JSONObject geometry = feature.getJSONObject("geometry");
					// JSONArray coordinates = geometry.getJSONArray("coordinates");
					// JSONArray coordinatesArray = coordinates.getJSONArray(0);
					// JSONArray nodeCoordinates = coordinatesArray.getJSONArray(0);
					
					JSONArray coordinatesArray = geometry.getJSONArray("coordinates");
					JSONArray nodeCoordinates = coordinatesArray.getJSONArray(0);

                    // System.out.println(" SENSA :: nodeCoordinates :: " + nodeCoordinates);

					Node nodeFrom = addNode(nodeCoordinates.getDouble(1), nodeCoordinates.getDouble(0), true, 0L, 0, 0L, 0);
					nodeCoordinates = coordinatesArray.getJSONArray(coordinatesArray.length() - 1);
					Node nodeTo = addNode(nodeCoordinates.getDouble(1), nodeCoordinates.getDouble(0), true, 0L, 0, 0L, 0);

					Link linkF = new Link();
					Link linkB = null;
					// link.setId(linkId++);
					if(properties.has("Shape_Leng")) linkF.setLength(properties.getDouble("Shape_Leng"));
                    if(properties.has("SPEEDKM")) linkF.setSpeed(properties.getDouble("SPEEDKM"));
					linkF.setNodeFrom(nodeFrom);
					linkF.setNodeTo(nodeTo);
					linkDao.insert(linkF);

					if (properties.getString("DIRECTION").equals("Two-ways")) {
						linkB = new Link();
						// link.setId(linkId++);
                        if(properties.has("Shape_Leng")) linkB.setLength(properties.getDouble("Shape_Leng"));
                        if(properties.has("SPEEDKM")) linkB.setSpeed(properties.getDouble("SPEEDKM"));
						linkB.setNodeFrom(nodeTo);
						linkB.setNodeTo(nodeFrom);
						linkDao.insert(linkB);
					}

					if (coordinatesArray.length() > 2) {
						for (int j = 1; j < coordinatesArray.length() - 1; j++) {
							nodeCoordinates = coordinatesArray.getJSONArray(j);
							if (properties.getString("DIRECTION").equals(
									"Two-ways")) {
								addNode(nodeCoordinates.getDouble(1),
										nodeCoordinates.getDouble(0), false,
										linkF.getId(), j, linkB.getId(),
										coordinatesArray.length() - (j + 1));
							} else {
								addNode(nodeCoordinates.getDouble(1),
										nodeCoordinates.getDouble(0), false,
										linkF.getId(), j, 0L, 0);
							}
						}
					}

                    // Progress Dialog - Loading
                    pDialog.setProgress(i+1);

				}

				Log.i("JSON", "Number of nodes: " + nodeDao.count() + "\nNumber of links: " + linkDao.count());

			} catch (JSONException e) {
				Log.i("JSON", e.getMessage());
				return false;
			}

			return true;
		}

		
		protected void onPostExecute(Boolean result) {
			pDialog.dismiss();
			if (result) {
				new AlertDialog.Builder(context)
						.setTitle(context.getResources().getString(R.string.download_routing_done))
						.setNegativeButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								}).show();

				new GetTripsTask(LoadActivity.this, email, password).execute();
			} else {
				new AlertDialog.Builder(context)
						.setTitle("JSON Exception")
						.setNegativeButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								}).show();
			}
		}

	}



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

		private Context context;

		public DownloadMapTask(LoadActivity activity) {
			super();
			context = activity;
		}

		ProgressDialog pDialog;

		protected void onPreExecute() {
			pDialog = new ProgressDialog(context);
			pDialog.setMessage("Downloading map...");
			pDialog.setProgressStyle(pDialog.STYLE_HORIZONTAL);
			pDialog.setCancelable(false);
			pDialog.setCanceledOnTouchOutside(false);
			pDialog.show();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			String jsonStr = null;

			// Create a new HttpClient and Post Header
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(
					"http://10.112.10.134/maps/kgalagadizoom/kgalagadi11-13.zip");

			try {
				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);

				// Get the string
				HttpEntity entity = response.getEntity();

				if (entity != null) {
					// A Simple JSON Response Read
					InputStream instream = entity.getContent();

					File root = Environment.getExternalStorageDirectory();
					File dir = new File(root.getAbsolutePath() + "/osmdroid");
					// dir.mkdirs();
					File file = new File(dir, "kgalagadi11-13.zip");

					FileOutputStream f = new FileOutputStream(file);

					// create a buffer...
					byte[] buffer = new byte[1024];
					int bufferLength = 0; // used to store a temporary size of
											// the buffer

					// this is the total size of the file
					long totalSize = entity.getContentLength();
					pDialog.setMax((int) totalSize);
					// variable to store total downloaded bytes
					int downloadedSize = 0;

					// now, read through the input buffer and write the contents
					// to the file
					while ((bufferLength = instream.read(buffer)) > 0) {
						// add the data in the buffer to the file in the file
						// output stream (the file on the sd card
						f.write(buffer, 0, bufferLength);

						// add up the size so we know how much is downloaded
						downloadedSize += bufferLength;
						// this is where you would do something to report the
						// prgress, like this maybe
						pDialog.setProgress(downloadedSize);
					}
					// close the output stream when done
					f.close();
				}

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				return false;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				return false;
			}

			return true;
		}

		protected void onPostExecute(Boolean result) {
			pDialog.dismiss();
			if (result) {
				new AlertDialog.Builder(context)
						.setTitle("Map successfully downloaded")
						.setNegativeButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								}).show();
			} else {
				new AlertDialog.Builder(context)
						.setTitle("Exception")
						.setNegativeButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								}).show();
			}
		}


	}

}
