/*
 * DownloadFilesTask.java
 * Task that parses the json file
 */

package com.cc.infosur.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.Timer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.cc.infosur.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;
import android.util.JsonReader;
import android.util.Log;

import com.cc.infosur.db.TestAdapter;
import com.cc.infosur.greendao.AlertDao;
import com.cc.infosur.greendao.ChatDao;
import com.cc.infosur.greendao.DaoMaster;
import com.cc.infosur.greendao.DaoMaster.DevOpenHelper;
import com.cc.infosur.greendao.Alert;
import com.cc.infosur.greendao.DaoSession;
import com.cc.infosur.greendao.Day;
import com.cc.infosur.greendao.DayDao;
import com.cc.infosur.greendao.DayServiceRel;
import com.cc.infosur.greendao.DayServiceRelDao;
import com.cc.infosur.greendao.DbLine;
import com.cc.infosur.greendao.DbLineDao;
import com.cc.infosur.greendao.DbPoint;
import com.cc.infosur.greendao.DbPointDao;
import com.cc.infosur.greendao.DbPolygon;
import com.cc.infosur.greendao.DbPolygonDao;
import com.cc.infosur.greendao.Detail;
import com.cc.infosur.greendao.DetailDao;
import com.cc.infosur.greendao.Excursion;
import com.cc.infosur.greendao.ExcursionDao;
import com.cc.infosur.greendao.Fauna;
import com.cc.infosur.greendao.FaunaDao;
import com.cc.infosur.greendao.Flora;
import com.cc.infosur.greendao.FloraDao;
import com.cc.infosur.greendao.Heritage;
import com.cc.infosur.greendao.HeritageDao;
import com.cc.infosur.greendao.MonthOpeningTime;
import com.cc.infosur.greendao.MonthOpeningTimeDao;
import com.cc.infosur.greendao.ParkInfo;
import com.cc.infosur.greendao.ParkInfoDao;
import com.cc.infosur.greendao.Question;
import com.cc.infosur.greendao.QuestionDao;
import com.cc.infosur.greendao.Questionary;
import com.cc.infosur.greendao.QuestionaryDao;
import com.cc.infosur.greendao.RequestDao;
import com.cc.infosur.greendao.Service;
import com.cc.infosur.greendao.ServiceDao;
import com.cc.infosur.greendao.Step;
import com.cc.infosur.greendao.StepDao;
import com.cc.infosur.greendao.Trip;
import com.cc.infosur.greendao.TripDao;

public class DownloadFilesTask extends AsyncTask<Void, Void, Boolean> {
	private SQLiteDatabase db;
	private DevOpenHelper helper;
	private DaoSession daoSession;
	private DaoMaster daoMaster;
	private TripDao tripDao;
	private StepDao stepDao;
	private ExcursionDao excursionDao;
	private DayDao dayDao;
	private ServiceDao serviceDao;
	private DetailDao detailDao;
	private DayServiceRelDao dayServiceRelDao;
	private DbPointDao pointDao;
	private DbLineDao lineDao;
	private DbPolygonDao polygonDao;
	private FloraDao floraDao;
	private FaunaDao faunaDao;
	private HeritageDao heritageDao;
	private ChatDao chatDao;
	private AlertDao alertDao;
	private QuestionaryDao questionaryDao;
	private QuestionDao questionDao;
	private ParkInfoDao parkInfoDao;
	private MonthOpeningTimeDao monthOpeningTimeDao;
    private RequestDao requestDao;

	private Context context;
	private TripListActivity tripListActivity;
    private LoadActivity lActivity;
	
	// FOR TESTING
	private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
	private AlarmManager alarmMgr;
	private PendingIntent alarmIntent;
	long month_opening_time;
	Date open_from;
	Date open_to;
	
	String jsonStr = null;
	String jsonStrTest = null;

    int etpParkId;
    int eppParkId;

    boolean isParkExist = true;

    /**
     * Constructor
     *
     * @param activity
     * @param json
     */
	public DownloadFilesTask(TripListActivity activity, String json) {
		super();
		context = activity;
		tripListActivity = activity;
		jsonStr = json;
	}


    /**
     * Function getByteArrayImageFromUrl()
     * @param imageUrl
     * @return
     */
	private byte[] getByteArrayImageFromUrl(String imageUrl) {
		DefaultHttpClient client = new DefaultHttpClient();
		byte[] imageBlob = null;
		try {
			HttpGet request = new HttpGet("http://sensa-prod3.tripalacarte.com/images/backofficeIMG/"+ URLEncoder.encode(imageUrl, "UTF-8").replace("+","%20"));
			HttpResponse response;
			response = client.execute(request);

			HttpEntity entity = response.getEntity();
			int imageLength = (int) (entity.getContentLength());
			InputStream is = entity.getContent();

			if (imageLength > 0) {
				imageBlob = new byte[imageLength];
				int bytesRead = 0;
				while (bytesRead < imageLength) {
					int n = is.read(imageBlob, bytesRead, imageLength- bytesRead);
					if (n <= 0)
						; // do some error handling
					bytesRead += n;
				}
			} else {
				return null;
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

		return imageBlob;
	}


    /**
     * 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();
	}

	ProgressDialog pDialog;



    /**
     * Function onPreExecute() - AsyncTask 1 / 3
     */
	protected void onPreExecute() {

		ConnectivityManager manager = (ConnectivityManager) context.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();
		
		// If No 3G & No WiFi
		if(!is3g && !isWifi) {
			new AlertDialog.Builder(context)
                .setTitle(context.getResources().getString(R.string.connexion_error))
                .setMessage(
						context.getResources().getString(R.string.check_connexion))
                .setNegativeButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        dialog.dismiss();
                                    }
                                }).show();
		// There is WiFi or 3G
        } else {
			
			pDialog = new ProgressDialog(context);
			pDialog.setMessage(context.getResources().getString(R.string.download_event));
			pDialog.setProgressStyle(pDialog.STYLE_HORIZONTAL);
			pDialog.setCancelable(false);
			pDialog.setCanceledOnTouchOutside(false);
			pDialog.setMax(100);
			pDialog.show();
		
		}
		
	}



    /**
     * Function doInBackground() - AsyncTask 2 / 3
      * @param params
     * @return
     *
     * Download and insert all the trip's data
     */
	@Override
	protected Boolean doInBackground(Void... params) {

		// Prepare db
		helper = new DaoMaster.DevOpenHelper(context, "tripdb", null);
		db = helper.getWritableDatabase();
		daoMaster = new DaoMaster(db);
		daoSession = daoMaster.newSession();
		tripDao = daoSession.getTripDao();
		stepDao = daoSession.getStepDao();
		excursionDao = daoSession.getExcursionDao();
		dayDao = daoSession.getDayDao();
		serviceDao = daoSession.getServiceDao();
		detailDao = daoSession.getDetailDao();
		dayServiceRelDao = daoSession.getDayServiceRelDao();
		pointDao = daoSession.getDbPointDao();
		lineDao = daoSession.getDbLineDao();
		polygonDao = daoSession.getDbPolygonDao();
		floraDao = daoSession.getFloraDao();
		faunaDao = daoSession.getFaunaDao();
		heritageDao = daoSession.getHeritageDao();
		chatDao = daoSession.getChatDao();
		alertDao = daoSession.getAlertDao();
		questionaryDao = daoSession.getQuestionaryDao();
		questionDao = daoSession.getQuestionDao();
		parkInfoDao = daoSession.getParkInfoDao();
		monthOpeningTimeDao = daoSession.getMonthOpeningTimeDao();
        requestDao = daoSession.getRequestDao();

		// Delete before load
		tripDao.deleteAll();
		stepDao.deleteAll();
		excursionDao.deleteAll();
		dayDao.deleteAll();
		serviceDao.deleteAll();
		detailDao.deleteAll();
		dayServiceRelDao.deleteAll();
		pointDao.deleteAll();
		lineDao.deleteAll();
		polygonDao.deleteAll();
		floraDao.deleteAll();
		faunaDao.deleteAll();
		heritageDao.deleteAll();
		chatDao.deleteAll();
		alertDao.deleteAll();
		questionaryDao.deleteAll();
		questionDao.deleteAll();
		parkInfoDao.deleteAll();
		monthOpeningTimeDao.deleteAll();
        requestDao.deleteAll();

		try {
            SimpleDateFormat format1 = new SimpleDateFormat("HH:mm:ssZZ");
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");

            Trip trip = new Trip();
			
			JSONObject jsonObject = new JSONObject(jsonStr);
			JSONObject tripObject = jsonObject.getJSONObject("message");


			// TESTING
			System.out.println(" SENSA :: DownloadFilesTask :: parks ");	
			
			// GET JSON ARRAY "PARKS"
			/////////////////////////
			JSONArray parks = tripObject.getJSONArray("parks");
			if (parks.length() > 0) {

                isParkExist =  true;

				
				JSONObject park = parks.getJSONObject(0);
				ParkInfo parkInfo = new ParkInfo();
				etpParkId = park.getInt("parkid");
				parkInfo.setEtpParkId(etpParkId);
				eppParkId = park.getInt("parkidEPP");
				parkInfo.setEppParkId(eppParkId);
				if (park.getInt("restricted") == 1)
					parkInfo.setRestricted(true);
				else
					parkInfo.setRestricted(false);
				parkInfoDao.insert(parkInfo);
				 
				
				// TESTING
				System.out.println(" SENSA :: DownloadFilesTask :: parkOpeningTimes ");	
				
				// Park opening times
				///SimpleDateFormat format1 = new SimpleDateFormat("HH:mm:ssZZ");
				///JSONArray parkOpeningTimes = getJsonArrayFromUrl("http://144.76.175.87/sensa/etp/getParkOpeningTimesJson.php?parkid="+ eppParkId);
				JSONArray parkOpeningTimes = getJsonArrayFromUrl("http://sensa-prod3.tripalacarte.com/frontend/json/getParkOpeningTimesJson.json");
				
				for (int i = 0; i < parkOpeningTimes.length(); i++) {
					JSONObject month = parkOpeningTimes.getJSONObject(i);

					MonthOpeningTime monthOpeningTime = new MonthOpeningTime();
					monthOpeningTime.setId(month.getLong("month"));
					monthOpeningTime.setOpenFrom(format1.parse(month.getString("open_from")));
					monthOpeningTime.setOpenTo(format1.parse(month.getString("open_to")));
					monthOpeningTime.setParkInfoId(parkInfo.getId());
					monthOpeningTimeDao.insert(monthOpeningTime);

                    System.out.println(" ------------------Sopen_from " + month.getString("month"));
                    System.out.println(" ------------------Sopen_from " + month.getString("open_from"));
                    System.out.println(" ------------------Sopen_from " + month.getString("open_to"));

				}


                /*MonthOpeningTime monthOpening1 = monthOpeningTimeDao.loadAll().get(1);
                System.out.println(" ***************************1 open_from= " + monthOpening1.getOpenFrom());
                System.out.println(" ***************************1 open_to= " + monthOpening1.getOpenTo());


                MonthOpeningTime monthOpening2 = monthOpeningTimeDao.loadAll().get(2);
                System.out.println(" ***************************2 open_from= " + monthOpening2.getOpenFrom());
                System.out.println(" ***************************2 open_to= " + monthOpening2.getOpenTo());



                MonthOpeningTime monthOpening3 = monthOpeningTimeDao.loadAll().get(3);
                System.out.println(" ***************************3 open_from= " + monthOpening3.getOpenFrom());
                System.out.println(" ***************************3 open_to= " + monthOpening3.getOpenTo());*/

				// TESTING
				System.out.println(" SENSA :: DownloadFilesTask :: limits ");	

					GetMapLayer getMapLayer = new GetMapLayer(3,
						parkInfo.getId(),
						pointDao, polygonDao, parkInfoDao);
						getMapLayers(etpParkId + "/" + park.getString("limits"),
						getMapLayer);
							
					if (parkInfo.getRestricted()) {
						
						// TESTING
						System.out.println(" 11111**********1SENSA :: DownloadFilesTask :: restricted_area "+park.getString("limits"));
					
						getMapLayer.setCategory(4);
						getMapLayers(
						etpParkId + "/" + park.getString("restricted_area"),
						getMapLayer);

                        // For Testing
                          // getMapLayer.setCategory(4);
                          // getMapLayers(
                          // "test/restricted.json",
                          // getMapLayer);

						// TESTING	
						System.out.println(" 222***********SENSA :: DownloadFilesTask :: accommodation_area "+park.getString("restricted_area"));
						
						getMapLayer.setCategory(5);
						getMapLayers(
						etpParkId + "/" + park.getString("accommodation_area"),
						getMapLayer);

                        // For Testing
                          // getMapLayer.setCategory(5);
                          // getMapLayers(
                          // "test/accommodation.json",
                          // getMapLayer);
					}

					
				// TESTING	
				System.out.println(" SENSA :: DownloadFilesTask :: parkWarningTimes ");


                try {
				
				// Park warning times
				//JSONArray parkWarningTimes = getJsonArrayFromUrl("http://144.76.175.87/sensa/etp/getParkWarningTimeJson.php?parkid="+eppParkId);
				JSONArray parkWarningTimes = getJsonArrayFromUrl("http://sensa-prod3.tripalacarte.com/frontend/json/getParkWarningTimeJson.json");
				
				JSONObject parkWarningTime = parkWarningTimes.getJSONObject(0);
				if( isNumeric(parkWarningTime.getString("timeout_timefencing_traveller")) ) {
					parkInfo.setTimeoutTimefencingTraveller(parkWarningTime.getInt("timeout_timefencing_traveller"));
				} else parkInfo.setTimeoutTimefencingTraveller(10);
				
				if( isNumeric(parkWarningTime.getString("timeout_geofencing_traveller")) ) {
					parkInfo.setTimeoutGeofencingTraveller(parkWarningTime.getInt("timeout_geofencing_traveller"));
				} else parkInfo.setTimeoutGeofencingTraveller(10);
					
				if( isNumeric(parkWarningTime.getString("timeout_tripviolation_traveller")) ) {
					parkInfo.setTimeoutTripviolationTraveller(parkWarningTime.getInt("timeout_tripviolation_traveller"));
				} else parkInfo.setTimeoutTripviolationTraveller(10);
			
				if( isNumeric(parkWarningTime.getString("timeout_timefencing_parkmanager")) ) {
					parkInfo.setTimeoutTimefencingParkmanager(parkWarningTime.getInt("timeout_timefencing_parkmanager"));
				} else parkInfo.setTimeoutTimefencingParkmanager(10);
				
				if( isNumeric(parkWarningTime.getString("timeout_geofencing_parkmanager")) ) {
					parkInfo.setTimeoutGeofencingParkmanager(parkWarningTime.getInt("timeout_geofencing_parkmanager"));
				} else parkInfo.setTimeoutGeofencingParkmanager(10);
					
				if( isNumeric(parkWarningTime.getString("timeout_tripviolation_parkmanager")) ) {
					parkInfo.setTimeoutTripviolationParkmanager(parkWarningTime.getInt("timeout_tripviolation_parkmanager"));
				} else parkInfo.setTimeoutTripviolationParkmanager(10);
				
				parkInfoDao.update(parkInfo);

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

            //
            //{
			// TESTING	
			System.out.println(" SENSA :: DownloadFilesTask :: TestAdapter :: layers ");

	        TestAdapter mDbHelper = new TestAdapter(context, "layers");        
	        mDbHelper.createDatabase(""+etpParkId, "layers");
	        mDbHelper.close();
	        
			
			
			// TESTING	
			System.out.println(" SENSA :: DownloadFilesTask :: TestAdapter :: routingdb ");

            //etpParkId = 246;

            mDbHelper = new TestAdapter(context, "routingdb");
	        mDbHelper.createDatabase(""+246, "routingdb");
            // mDbHelper.createDatabase(""+etpParkId, "routingdb");
	        mDbHelper.close();

			// TESTING	
			System.out.println(" SENSA :: DownloadFilesTask :: Getting trip data ");


            }

            else
            {
                isParkExist =  false;
            }
			
			
			///SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");

			///Trip trip = new Trip();
			trip.setId(tripObject.getLong("id"));
			trip.setName(tripObject.getString("name"));
			// trip.setVersion(tripObject.getInt("version"));
			trip.setDateFrom(format2.parse(tripObject.getString("dateFrom")));
			trip.setDateTo(format2.parse(tripObject.getString("dateTo")));

            // TESTING
			System.out.println(" SENSA :: DownloadFilesTask :: Service ");	
			

			// GET ARRAY JSON "SERVICES"
			////////////////////////////
			pDialog.setMax(tripObject.getJSONArray("services").length()
			+ tripObject.getJSONArray("calendar").length()+tripObject.getJSONArray("steps").length());

			JSONArray services = tripObject.getJSONArray("services");
			for (int i = 0; i < services.length(); i++) {
				JSONObject serviceObject = services.getJSONObject(i);
				Service service = new Service();
				
				// TESTING
				service.setId(serviceObject.getLong("idreservation"));
				//service.setIdserviceepp(serviceObject.getLong("idserviceEPP"));
				service.setName(serviceObject.getString("name"));
				//service.setType(serviceObject.getInt("type"));
				service.setType(serviceObject.getInt("thematic"));
				service.setLocality(serviceObject.getString("servicelocality"));
				// temporal

				try {
					service.setLatitude(serviceObject.getDouble("geoloclat"));
					service.setLongitude(serviceObject.getDouble("geoloclong"));
				} catch (JSONException e) {
					//service.setLatitude(-25.80);
					//service.setLongitude(20.10);
				}

				service.setStartHour(serviceObject.getString("startHour"));
				
				System.out.println(" SENSA :: DownloadFilesTask :: startHour :: " + serviceObject.getString("startHour"));
				
				service.setIcon(getByteArrayImageFromUrl("thumbs/" + serviceObject.getString("icon")));
				service.setAvailable(true);
				service.setActivated(false);

				// if (service.getId() == 3078L){
				// service.setAvailable(false);
				// }

				// TESTING	
				System.out.println(" SENSA :: DownloadFilesTask :: Geometry ");	
				
				if (!serviceObject.isNull("geometry")) {
					JSONObject geometry = serviceObject.getJSONObject("geometry");

					if (geometry.getString("type").equals("MultiLineString") ) {
							 // || geometry.getString("type").equals("LineString")) {
						service.setServiceMap(1); // 1: line
						
						

						// TESTING	
						System.out.println(" SENSA :: DownloadFilesTask :: Geometry :: MultiLineString && LineString :: Coordinates");	

						
						// GET ARRAY JSON "COORDINATES"
						///////////////////////////////
						JSONArray coordinatesArray = geometry.getJSONArray("coordinates");
						for (int k = 0; k < coordinatesArray.length(); k++) {


                            // System.out.println(" ********************** coordinatesArray :: " + coordinatesArray.length());

                            DbLine line = new DbLine();
							line.setServiceId(service.getId());
							lineDao.insert(line);

							JSONArray coordinates = coordinatesArray.getJSONArray(k);
							for (int q = 0; q < coordinates.length(); q++) {

                                // System.out.println(" ********************** coordinates :: " + coordinates.length());
                                // System.out.println(" ====================== coordinates.optJSONArray(q) :: " + coordinates.optJSONArray(q));

                                //JSONArray arrCoord = coordinates.optJSONArray(q);

								JSONArray coord = coordinates.getJSONArray(q);
								DbPoint point = new DbPoint();
								point.setLatitude(coord.getDouble(1));
								point.setLongitude(coord.getDouble(0));
								point.setLineId(line.getId());
								pointDao.insert(point);
							}
							lineDao.update(line);
						}
					} else if (geometry.getString("type")
							.equals("MultiPolygon")
							|| geometry.getString("type").equals("Polygon")) {
						service.setServiceMap(2); // 2: polygon

						

						// TESTING	
						System.out.println(" SENSA :: DownloadFilesTask :: Geometry :: MultiPolygon && Polygon :: Coordinates");	
						
						
						// GET ARRAY JSON "COORDINATES"
						///////////////////////////////
						JSONArray coordinatesArray = geometry
								.getJSONArray("coordinates");
						DbPolygon polygon = new DbPolygon();
						polygonDao.insert(polygon);
						service.setPolygon(polygon);

						JSONArray coordinates = coordinatesArray.getJSONArray(0);
						JSONArray coordin = coordinates.getJSONArray(0);
						for (int q = 0; q < coordin.length(); q++) {
							JSONArray coord = coordin.getJSONArray(q);
							DbPoint point = new DbPoint();
							point.setLatitude(coord.getDouble(1));
							point.setLongitude(coord.getDouble(0));
							point.setPolygonId(polygon.getId());
							pointDao.insert(point);
						}
						polygonDao.update(polygon);
					} else
						service.setServiceMap(0); // 0: point
				} else {
					service.setServiceMap(0); // 0: point
				}

				
				
				
				// TESTING	
				System.out.println(" SENSA :: DownloadFilesTask :: Documents");	
			
				
				
				// GET ARRAY JSON "DOCUMENTS"
				////////////////////////////
				JSONArray detailsArray = serviceObject
						.getJSONArray("documents");
				for (int k = 0; k < detailsArray.length(); k++) {
					JSONObject detailObject = detailsArray.getJSONObject(k);
					Detail detail = new Detail();
					detail.setDetailOrder(detailObject.getInt("order"));
					detail.setFulldescr(detailObject.getString("description"));
					detail.setPicture(getByteArrayImageFromUrl(detailObject
							.getString("file")));
					System.out.println("JSON::services::documents::picture --> " + detailObject
							.getString("file")) ;
					detail.setServiceId(service.getId());
					detailDao.insert(detail);
				}
				serviceDao.insert(service);
				pDialog.incrementProgressBy(1);
			}

			
			
			
			// TESTING	
			System.out.println(" SENSA :: DownloadFilesTask :: Alternatives");	
			
			
			for (int i = 0; i < services.length(); i++) {
				JSONObject serviceObject = services.getJSONObject(i);
				
				// GET ARRAY JSON "ALTERNATIVES"
				////////////////////////////////
				JSONArray alternatives = serviceObject
						.getJSONArray("alternatives");
				if (alternatives.length() == 0){
					Log.i("ALTERNATIVES", "service " + serviceObject.getLong("idreservation") + " no alternatives");
					continue;
				}
				Service service = serviceDao.load(serviceObject
						.getLong("idreservation"));
				for (int j = 0; j < alternatives.length(); j++) {
					Service alternativeService = serviceDao.load(alternatives
							.getLong(j));
					alternativeService.setAlternativeServiceId(service.getId());
					serviceDao.update(alternativeService);
				}
				serviceDao.update(service);
				pDialog.incrementProgressBy(1);
			}

			
			
			
			// TESTING	
			System.out.println(" SENSA :: DownloadFilesTask :: Calendar");	
			
			// GET ARRAY JSON "CALENDAR"
			////////////////////////////
			JSONArray calendar = tripObject.getJSONArray("calendar");
			for (int i = 0; i < calendar.length(); i++) {
				JSONObject dayObject = calendar.getJSONObject(i);
				Day day = new Day();
				day.setId((long) i + 1);
				day.setPark(dayObject.getInt("park"));
				day.setDay(format2.parse(dayObject.getString("date")));

				
				
				// TESTING	
				System.out.println(" SENSA :: DownloadFilesTask :: Calendar :: Services");	
				
				
				// GET ARRAY JSON "SERVICES"
				////////////////////////////
				JSONArray servicesArray = dayObject.getJSONArray("services");
				for (int j = 0; j < servicesArray.length(); j++) {
					DayServiceRel dayServiceRel = new DayServiceRel();
					dayServiceRel.setDay(day.getId());
					dayServiceRel.setService(servicesArray.getLong(j));
					dayServiceRel.setOrder(j);
					dayServiceRelDao.insert(dayServiceRel);

					Service service = serviceDao.load(servicesArray.getLong(j));
					service.setDayId(day.getId());
					serviceDao.update(service);
				}
				day.setTripId(trip.getId());
				dayDao.insert(day);
				pDialog.incrementProgressBy(1);
			}

			
			

			
			// TESTING	
			System.out.println(" SENSA :: DownloadFilesTask :: Steps ");	
			
			
			
			// GET ARRAY JSON "STEPS"
			/////////////////////////
			JSONArray steps = tripObject.getJSONArray("steps");
			Long excursionId = (long) 1;
			for (int i = 0; i < steps.length(); i++) {
				JSONObject stepObject = steps.getJSONObject(i);
				Step step = new Step();
				step.setId(stepObject.getLong("orderstep"));
				step.setName(stepObject.getString("name"));
				//step.setLatitude(stepObject.getDouble("geoloclat"));
				//step.setLongitude(stepObject.getDouble("geoloclong"));
				step.setDateFrom(format2.parse(stepObject.getString("dateFrom")));
				step.setDateTo(format2.parse(stepObject.getString("dateTo")));
				step.setIcon(getByteArrayImageFromUrl("thumbs/"
						+ stepObject.getString("icon")));

				
				try {
					step.setLatitude(stepObject.getDouble("geoloclat"));
					step.setLongitude(stepObject.getDouble("geoloclong"));
				} catch (JSONException e) {
					//step.setLatitude(-25.80);
					//step.setLongitude(20.10);
				}
				
				
				
				Detail detail = new Detail();
				detail.setDetailOrder(0);
				detail.setFulldescr(stepObject.getString("description"));
				detail.setPicture(getByteArrayImageFromUrl(stepObject.getString("picture")));
				System.out.println("JSON::steps::picture --> " + stepObject.getString("picture")) ;
				detail.setStepId(step.getId());
				detailDao.insert(detail);

				
				
				// TESTING	
				System.out.println(" SENSA :: DownloadFilesTask :: Steps :: Excursions ");	
				
				
		
				
				// GET ARRAY JSON "EXCURSIONS"
				//////////////////////////////
				JSONArray excursionsArray = stepObject
						.getJSONArray("excursions");
				for (int j = 0; j < excursionsArray.length(); j++) {
					JSONObject excursionObject = excursionsArray
							.getJSONObject(j);
					Excursion excursion = new Excursion();
					excursion.setId(excursionId++);
					excursion.setExcursionOrder(excursionObject.getInt("id"));
					excursion.setName(excursionObject.getString("name"));
					excursion.setRegion(excursionObject.getString("region"));
					// excursion.setLatitude(excursionObject.getDouble("geoloclat"));
					// excursion.setLongitude(excursionObject.getDouble("geoloclong"));

					JSONArray servicesArray = excursionObject
							.getJSONArray("services");
					for (int k = 0; k < servicesArray.length(); k++) {
						Service service = serviceDao.load(servicesArray
								.getLong(k));
						service.setExcursionId(excursion.getId());
						serviceDao.update(service);
					}
					// excursion.setStep(step);
					excursion.setStepId(step.getId());
					excursionDao.insert(excursion);
				}
				step.setTripId(trip.getId());
				stepDao.insert(step);
				pDialog.incrementProgressBy(1);
			}

			
			// TESTING	
			System.out.println(" SENSA :: DownloadFilesTask :: Maplayers ");

            if(isParkExist)
            {
			
			//if (false) {
				JSONObject mapLayers = tripObject.getJSONObject("maplayers");
				JSONObject parkMapLayers = mapLayers.getJSONObject(etpParkId+ "");

				// CHECK IF THERE IS "FLORA"
				JSONArray arrFlora = parkMapLayers.optJSONArray("flora");
				if(arrFlora != null) {
				//if(parkMapLayers.has("flora")) {
					JSONArray floraArray = parkMapLayers.getJSONArray("flora");
					for (int i = 0; i < floraArray.length(); i++) {
						JSONObject floraObject = floraArray.getJSONObject(i);
						if (floraObject.getString("name").equals("landcover_general"))
							continue;

                            Flora flora = new Flora();

                            // TESTING
                            System.out.println(" ****** MAPLAYERS :: " + etpParkId + " :: FLORA :: " + floraObject.getString("name") );

                            flora.setSpecie(floraObject.getString("name"));
                            flora.setIcon(getByteArrayImageFromUrl("thumbs/"+ floraObject.getString("icon")));
                            floraDao.insert(flora);

                            JSONArray detailsArray = floraObject.getJSONArray("description");
                            for (int k = 0; k < detailsArray.length(); k++) {

                                JSONObject detailObject = detailsArray.getJSONObject(k);
                                Detail detail = new Detail();
                                detail.setDetailOrder(detailObject.getInt("order"));
                                detail.setFulldescr(detailObject.getString("description"));

                                detail.setPicture(getByteArrayImageFromUrl(detailObject.getString("file")));
                                detail.setFloraId(flora.getId());
                                detailDao.insert(detail);
                            }

                            GetMapLayer getMapLayer = new GetMapLayer(0, flora.getId(), pointDao, polygonDao, parkInfoDao);

                            getMapLayers(
                                etpParkId + "/" + floraObject.getString("source"),
                                getMapLayer);

                        floraDao.update(flora);

					}
				} else {
					System.out.println("SENSA :: LAYER : NO FLORA");
				}


				// TESTING	
				System.out.println(" SENSA :: DownloadFilesTask :: Maplayers :: fauna");	
				
				
		
				// CHECK IF THERE "FAUNA"
				JSONArray arrFauna = parkMapLayers.optJSONArray("fauna");
				if(arrFauna != null) {
				//if(parkMapLayers.has("fauna")) {
					JSONArray faunaArray = parkMapLayers.getJSONArray("fauna");
					for (int i = 0; i < faunaArray.length(); i++) {
						JSONObject faunaObject = faunaArray.getJSONObject(i);
						if (faunaObject.getString("name").equals("4"))
							continue;
						Fauna fauna = new Fauna();

                        // TESTING
                        System.out.println(" ****** MAPLAYERS :: " + etpParkId + " :: FAUNA :: " + faunaObject.getString("name") );


                        fauna.setSpecie(faunaObject.getString("name"));
						fauna.setIcon(getByteArrayImageFromUrl("thumbs/"+ faunaObject.getString("icon")));
						faunaDao.insert(fauna);
	
						JSONArray detailsArray = faunaObject.getJSONArray("description");
						for (int k = 0; k < detailsArray.length(); k++) {
							JSONObject detailObject = detailsArray.getJSONObject(k);
							Detail detail = new Detail();
							detail.setDetailOrder(detailObject.getInt("order"));
							detail.setFulldescr(detailObject.getString("description"));
							detail.setPicture(getByteArrayImageFromUrl(detailObject.getString("file")));
							detail.setFaunaId(fauna.getId());
							detailDao.insert(detail);
						}
	
						GetMapLayer getMapLayer = new GetMapLayer(1, fauna.getId(),
								pointDao, polygonDao, parkInfoDao);

	
						if (getMapLayers(
								etpParkId + "/" + faunaObject.getString("source"),
								getMapLayer))
							faunaDao.update(fauna);
						else
							faunaDao.delete(fauna);
					}
				} else {
					System.out.println("SENSA :: LAYER : NO FAUNA");
				}

				
				// TESTING	
				System.out.println(" SENSA :: DownloadFilesTask :: Maplayers :: heritage");	

				
				// CHECK IF THERE IS "HERITAGE"
				JSONArray arrHeritage = parkMapLayers.optJSONArray("heritage");
				if(arrHeritage != null) {
				//if(parkMapLayers.has("heritage")) {
					JSONArray heritageArray = parkMapLayers.getJSONArray("heritage");
					for (int i = 0; i < heritageArray.length(); i++) {
						JSONObject heritageObject = heritageArray.getJSONObject(i);
						Heritage heritage = new Heritage();
						heritage.setName(heritageObject.getString("name"));
						heritage.setIcon(getByteArrayImageFromUrl("thumbs/"
								+ heritageObject.getString("icon")));
						heritageDao.insert(heritage);
	
						JSONArray detailsArray = heritageObject
								.getJSONArray("description");
						for (int k = 0; k < detailsArray.length(); k++) {
							JSONObject detailObject = detailsArray.getJSONObject(k);
							Detail detail = new Detail();
							detail.setDetailOrder(detailObject.getInt("order"));
							detail.setFulldescr(detailObject
									.getString("description"));
							detail.setPicture(getByteArrayImageFromUrl(detailObject
									.getString("file")));
							detail.setHeritageId(heritage.getId());
							detailDao.insert(detail);
						}
	
						GetMapLayer getMapLayer = new GetMapLayer(2,
								heritage.getId(), pointDao, polygonDao, parkInfoDao);
	
						if (getMapLayers(
								etpParkId + "/"
										+ heritageObject.getString("source"),
								getMapLayer))
							heritageDao.update(heritage);
						else
							heritageDao.delete(heritage);
					}
				} else {
					System.out.println("SENSA :: LAYER : NO HERITAGE");
				}


      }
			//}


			tripDao.insert(trip);
			
        /*  //TODO To be fixed !!!

			// Alerts
			try {
				HttpGet httpget = new HttpGet(
						"http://144.76.175.87/sensa/etp/getAlertsJson.php?parkid="+eppParkId);
				HttpClient httpclient = new DefaultHttpClient();
				HttpResponse response = httpclient.execute(httpget);

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

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

			} catch (ClientProtocolException e) {
				return null;
			} catch (IOException e) {
				return null;
			}

			JSONObject alertsObject = new JSONObject(jsonStr);
			JSONArray alertsArray = alertsObject.getJSONArray("alerts");
			for (int i = 0; i < alertsArray.length(); i++) {
				try {
					JSONObject a = alertsArray.getJSONObject(i);
					Alert alert = new Alert();
					alert.setId(a.getLong("id"));
					alert.setName(a.getString("name"));
					alert.setType(a.getInt("type"));
					alert.setDescription(a.getString("description"));
					// TEST
					alert.setLatitude(0D);
					alert.setLongitude(0D);
					alert.setRadius(0);
					alert.setDate(Calendar.getInstance().getTime());
					alertDao.insert(alert);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
        */



            if(isParkExist)
            {

			// Questions
			try {

                // For Testing
				    //String http = "http://10.112.10.132/maps/questions.json";
				
				///HttpGet httpget = new HttpGet("http://144.76.175.87/sensa/etp/getFieldReportQuestion.php?parkid="+eppParkId);



                HttpGet httpget = new HttpGet("http://144.76.175.87/sensa/etp/getFieldReportQuestion.php?parkid="+eppParkId+"&lang=en&valid_from='2015-05-01'&valid_to='2015-12-30'");

				HttpClient httpclient = new DefaultHttpClient();
				HttpResponse response = httpclient.execute(httpget);

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

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

			} catch (ClientProtocolException e) {
				return null;
			} catch (IOException e) {
				return null;
			}

		
			JSONObject questionsObject = new JSONObject(jsonStr);

			
			// TESTING	
			System.out.println(" SENSA :: DownloadFilesTask :: Maplayers :: Questions");
			
			
			JSONArray questionsArray = questionsObject.getJSONArray("questions");
			for (int i = 0; i < questionsArray.length(); i++) {
					JSONObject q = questionsArray.getJSONObject(i);
					Questionary questionary = new Questionary();
					questionary.setText(q.getString("text"));
					if (q.getInt("photo")==1){
						questionary.setType(0);
					}
					else questionary.setType(1);
					questionary.setLatitude(q.getDouble("geoloclat"));
					questionary.setLongitude(q.getDouble("geoloclon"));
					questionary.setRadius(q.getInt("radius"));
					questionary.setActivated(false);
					questionaryDao.insert(questionary);
					
					JSONArray speciesArray = q.getJSONArray("species");
					for (int j=0; j < speciesArray.length(); j++){
						JSONObject s = speciesArray.getJSONObject(j);
						Question question = new Question();
						//question.setId(s.getLong("id"));///
                        question.setId(q.getLong("questionid"));///
						question.setTitle(s.getString("name"));
						question.setQuestionaryId(questionary.getId());
						question.setSelected(false);
						question.setPhotoTaken(false);
						question.setQuantity(0);
						questionDao.insert(question);
					}
					
					questionaryDao.update(questionary);
					
			}


            }
            //new LoadRoutingTask(lActivity).execute();

	
		} catch (JSONException e) {
			Log.i("MAIN", "exception");
			e.printStackTrace();
			return false;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}



		return true;
	}


    /**
     * Function getJsonArrayFromUrl()
     * @param url
     * @return
     */
	private JSONArray getJsonArrayFromUrl(String url) {
		String jsonStr = null;
		try {

			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(url);

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

			// 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();
			}

			return new JSONArray(jsonStr);

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	
	public static boolean isNumeric(String str) { 
		
		  try {  
		    double d = Double.parseDouble(str);  
		  } catch(NumberFormatException nfe) {  
		    return false;  
		  }
		  
		  return true;  
	}



    /**
     * Function getMapLayers()
     * @param jsonFile
     * @param getMapLayer
     * @return
     *
     * Download layers from our own server http://sensa-demo.tripalacarte.com
     */
	private boolean getMapLayers(String jsonFile, GetMapLayer getMapLayer) {

		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost;

		try {

			URL url = new URL("http://sensa-prod3.tripalacarte.com/frontend/json/parks/"+ URLEncoder.encode(jsonFile, "UTF-8").replace("+","%20"));
			URLConnection urlConnection = url.openConnection();
			urlConnection.connect();
			int file_size = urlConnection.getContentLength();
			Log.i("FILEJSON", "// File: " + jsonFile + " // Size: " + file_size + " // GetMapLayer: " + getMapLayer);

            // Maximum size of a json FILE // 3000000
			if (file_size > 300000)
				return false;

			httppost = new HttpPost("http://sensa-prod3.tripalacarte.com/frontend/json/parks/"+ URLEncoder.encode(jsonFile, "UTF-8").replace("+","%20"));

			System.out.println("SENSA :: DownloadFilesTask :: GetMapLayers :: execute");

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


			System.out.println("SENSA :: DownloadFilesTask :: GetMapLayers :: responce");
			// Get the string
			HttpEntity entity = response.getEntity();

			

			System.out.println("SENSA :: DownloadFilesTask :: GetMapLayers :: entity != null");
			
			
			if (entity != null) {
				// A Simple JSON Response Read
				InputStream instream = entity.getContent();
				if (getMapLayer.readJsonStream(instream)) {
					instream.close();
					return true;
				} else {
					instream.close();
					return false;
				}

			}

		} catch (ClientProtocolException e) {
			return false;
		} catch (IOException e) {
			return false;
		}

		return true;
	}


    /**
     * Function onPostExecute() - AsyncTask 3 / 3
     * @param result
     */
	protected void onPostExecute(Boolean result) {
		pDialog.dismiss();
		if (result)
			tripListActivity.showTrip(eppParkId, etpParkId);
		else {
			new AlertDialog.Builder(context)
					.setTitle(context.getResources().getString(R.string.connexion_error))
					.setMessage(
							"Something happened. Please contact your tour operator")
					.setNegativeButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							}).show();
		}                      
	}


    /**
     * Function showNotification()
     * @param type
     * @param title
     * @param message
     *
     * Send a notification to the traveler
     */
	private void showNotification(String type, String title, String message) {

		Intent intent = new Intent(context, MainActivity.class);

        intent.setFlags(intent.FLAG_ACTIVITY_SINGLE_TOP);


		intent.putExtra("type", type);
		// intent.setAction(Intent.ACTION_MAIN);
		// intent.addCategory(Intent.CATEGORY_LAUNCHER);
		PendingIntent contentIntent = PendingIntent.getActivity(context, 5,
				intent, PendingIntent.FLAG_UPDATE_CURRENT
						| PendingIntent.FLAG_ONE_SHOT);

		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				context).setSmallIcon(R.drawable.sensa_logo)
				.setContentTitle(title).setContentText(message);
		mBuilder.setContentIntent(contentIntent);
		mBuilder.setDefaults(Notification.DEFAULT_SOUND);
		mBuilder.setAutoCancel(true);
		NotificationManager mNotificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.notify(1, mBuilder.build());
	}



    private Calendar DateToCalendar(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal;
    }

}
