/*
 * MyTripFragment.java
 * Displays the trip summary
 */

package com.cc.infosur.mytrip;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cc.infosur.greendao.DaoMaster;
import com.cc.infosur.greendao.DaoMaster.DevOpenHelper;
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.DayServiceRelDao.Properties;
import com.cc.infosur.greendao.Detail;
import com.cc.infosur.greendao.Excursion;
import com.cc.infosur.greendao.Service;
import com.cc.infosur.greendao.ServiceDao;
import com.cc.infosur.greendao.Step;
import com.cc.infosur.greendao.Trip;
import com.cc.infosur.greendao.TripDao;
import com.cc.infosur.main.MainActivity;
import com.cc.infosur.main.PubFragment;
import com.cc.infosur.map.InfoFragment;
import com.cc.infosur.map.MapFragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import com.cc.infosur.R;

public class MyTripFragment extends Fragment {
	public MainActivity mActivity;
	public Bundle bn;
	private ImageView goToDayButton;

	// Database variables
	private SQLiteDatabase db;
	private DevOpenHelper helper;
	private DaoSession daoSession;
	private DaoMaster daoMaster;
	private TripDao tripDao;
	private DayServiceRelDao dayServiceRelDao;
	private DayDao dayDao;
	private ServiceDao serviceDao;

    private List<Day> days;
    private int dayNo;

    private LocationManager lm;
    private Context context;

	Trip trip;
	LayoutInflater inflater;
	LinearLayout stepListLayout;

    public final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    /**
     * Function onConfigurationChanged()
     * @param newConfig
     */
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Reload current fragment
		final FragmentTransaction ft = getFragmentManager().beginTransaction();
		ft.detach(this);
		ft.attach(this);
		//ft.commit();
        ft.commitAllowingStateLoss();
    }



    /**
     * Function onCreate()
     * @param savedInstanceState
     */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Log.i("MYTRIP", "onCreate");
	}



    /**
     * Function onCreateView()
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		// Inflate the layout for this fragment
		View V = inflater.inflate(R.layout.tripsummary, container, false);
		Log.i("MYTRIP", "onCreateView");

		this.inflater = inflater;

		mActivity = (MainActivity) this.getActivity();

        final MainActivity mainActivity = MainActivity.getInstance();

		// Get buttons, textview and layouts
		goToDayButton = (ImageView) V.findViewById(R.id.goToDayButton);
		goToDayButton.setOnClickListener(listener);

		stepListLayout = (LinearLayout) V.findViewById(R.id.stepListLayout);

		TextView textNameTrip = (TextView)V.findViewById(R.id.textTripDays);
		TextView textDateTrip = (TextView)V.findViewById(R.id.textNameTrip);

		// Logout button
		ImageView logoutButton = (ImageView) V.findViewById(R.id.logoutButton);
		logoutButton.setOnClickListener(new OnClickListener() {

		    @Override
			public void onClick(View arg0) {
				new AlertDialog.Builder(mActivity)
						.setTitle(mActivity.getResources().getString(R.string.logout))
						.setMessage(mActivity.getResources().getString(R.string.logout_mess))
						.setPositiveButton("Non",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								})
						.setNegativeButton("Oui",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										mActivity.logout();
									}
								}).show();
			}

		});

		
		// Prepare db
		helper = new DaoMaster.DevOpenHelper(getActivity(), "tripdb", null);
		db = helper.getWritableDatabase();
		daoMaster = new DaoMaster(db);
		daoSession = daoMaster.newSession();
		tripDao = daoSession.getTripDao();
		dayServiceRelDao = daoSession.getDayServiceRelDao();
		dayDao = daoSession.getDayDao();
		serviceDao = daoSession.getServiceDao();

		trip = tripDao.loadAll().get(0);

        // Get list days of this trip user
        days = trip.getDays();

		textNameTrip.setText(trip.getName());
		SimpleDateFormat ffr = new SimpleDateFormat("dd MMMM yyyy", new Locale("fr"));
		textDateTrip.setText(ffr.format(trip.getDateFrom()));

        try {
			loadTripSummary();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        lm = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);

        Criteria criteria = new Criteria();
        String provider = lm.getBestProvider(criteria, true);
        Location loc = lm.getLastKnownLocation(provider);

        System.out.println("--------------------------loc="+loc);

        /*if((loc == null)||((loc.getLongitude() == 0.0)&&(loc.getLatitude() == 0.0)))
        {
            System.out.println("----------------FOUND");

            showNotification("Location not known", "Location not known", "Enable your GPS position and go outside");

            showPosotionDialog();
        }*/

        return V;
	}

    /**
     * Function loadTripSummary()
     */
	private void loadTripSummary() {
		//Function that loads the steps and services names and displays them in the steps layout
		
		stepListLayout.removeAllViews();

		List<Step> steps = trip.getSteps();
		LinearLayout stepsLayout = null;
		LinearLayout layoutServices;
		LinearLayout serviceNameLayout;
		String currentRegion = "";
		for (int i = 0; i < steps.size(); i++) {
			List<Excursion> excursions = steps.get(i).getExcursions();
			for (int j = 0; j < excursions.size(); j++) {
				if (excursions.get(j).getName().equals("main")) {
					stepsLayout = (LinearLayout) inflater.inflate(
							R.layout.stepslayout, null);
					layoutServices = (LinearLayout) stepsLayout
							.findViewById(R.id.activitiesLayout);
					TextView tv = (TextView) stepsLayout
							.findViewById(R.id.stepNumberTextView);

					tv.setText(Integer.toString(i + 1));

					tv = (TextView) stepsLayout
							.findViewById(R.id.stepNameTextView);
					//TODO Here is the display of the steps
                    //calcul nb jour
                    Calendar calendar1 = Calendar.getInstance();
                    Calendar calendar2 = Calendar.getInstance();
                    calendar1.setTime(steps.get(i).getDateTo());
                    calendar2.setTime(steps.get(i).getDateFrom());
                    long milliseconds1 = calendar1.getTimeInMillis();
                    long milliseconds2 = calendar2.getTimeInMillis();
                    long diff = milliseconds1 - milliseconds2;
                    long numberOfDay = diff / (24 * 60 * 60 * 1000);
                    if(numberOfDay == 1){
                        tv.setText(steps.get(i).getName());//+" - "+numberOfDay+" day");
                    }else{
                        tv.setText(steps.get(i).getName());//+" - "+numberOfDay+" days");
                    }

                    Bitmap bmp = BitmapFactory.decodeByteArray(steps.get(i)
							.getIcon(), 0, steps.get(i).getIcon().length);
					ImageView iv = (ImageView) stepsLayout
							.findViewById(R.id.stepImage);
					iv.setImageBitmap(bmp);
					iv.setOnClickListener(new StepDescriptionClickListener(
							steps.get(i)));
					if (!excursions.get(j).getRegion().equals(currentRegion)) {
						tv = (TextView) stepsLayout
								.findViewById(R.id.regionNameTextView);
						tv.setText(excursions.get(j).getRegion());
						currentRegion = excursions.get(j).getRegion();
						tv.setVisibility(View.VISIBLE);
					}
				} else {
					stepsLayout = (LinearLayout) inflater.inflate(
							R.layout.excursionslayout, null);
					layoutServices = (LinearLayout) stepsLayout
							.findViewById(R.id.activitiesLayout);
					TextView tv = (TextView) stepsLayout
							.findViewById(R.id.excursionNameTextView);
					tv.setText(excursions.get(j).getName());
					Log.i("INFOLOG-name",excursions.get(j).getName());
					/*** PART FOR PORTO IMAGE***/
					if(excursions.get(j).getIcon()!=null) {
						Bitmap bmp = BitmapFactory.decodeByteArray(excursions.get(j)
								.getIcon(), 0, excursions.get(j).getIcon().length);
						//stepsLayout = (LinearLayout) inflater.inflate(
						//R.layout.stepslayout, null);
						ImageView iv = (ImageView) stepsLayout
								.findViewById(R.id.stepImage);
						if(bmp != null) {
							iv.setImageBitmap(bmp);
							iv.setOnClickListener(new ExcursionDescriptionClickListener(
									excursions.get(j)));
						}
					}
				}
				View v = inflater.inflate(R.layout.tripsummary, null);
				TextView txtTripDays = (TextView) v.findViewById(R.id.textTripDays);
				//txtTripDays.setText(nbDay + " DAYS TRIP");

				List<Service> services = excursions.get(j).getServices();
				for (int k = 0; k < services.size(); k++) {
					if(services.get(k).getType() != 2){
					serviceNameLayout = (LinearLayout) inflater.inflate(R.layout.servicenamelayout, null);

					TextView tv3 = (TextView) serviceNameLayout.findViewById(R.id.nameServiceTextView);

                    //ImageButton ib = (ImageButton) serviceNameLayout.findViewById(R.id.arrowService);
					System.out.println("----------------- SERVICE NAME : "+services.get(k).getName());

					if (services.get(k).getAvailable()) {
						tv3.setText(services.get(k).getName());
					} else {
						boolean activated = false;
						if (services.get(k).getAlternativeServices().size() > 0) {
							for (Service service : services.get(k)
									.getAlternativeServices()) {
								if (service.getActivated()) {
									tv3.setText("Alternative activity: "
											+ service.getName());
									activated = true;
									service.update();
									break;
								}
							}
							if (!activated) {
								Service service = services.get(k)
										.getAlternativeServices().get(0);
								service.setActivated(true);
								service.update();
								tv3.setText("Alternative activity: "
										+ service.getName());
							}
							tv3.setTextColor(Color.BLUE);
							final int dayNo = trip.getDays().indexOf(
									dayDao.load(getFirstDayOfService(services
											.get(k).getId())));
							tv3.setOnClickListener(new View.OnClickListener() {
								@Override
								public void onClick(View v) {
									DayFragment fg = new DayFragment();
									fg.setDayNo(dayNo);
									//mActivity.pushFragments("MYTRIP_TAB", fg, mActivity.mStacks.get("MYTRIP_TAB").lastElement(), true);
								}
							});
						} else {
							Log.i("ALTERNATIVE", "Service "
									+ services.get(k).getId()
									+ " n of alternatives: 0");
						}
					}
                   try
				   {
						 tv3.setOnTouchListener(new ServiceDescriptionTouchListener(services.get(k).getId()));
						 layoutServices.addView(serviceNameLayout);
						 layoutServices.addView(serviceNameLayout);
				   }catch (Exception e) {
                        e.printStackTrace();
				   }}
				}
				stepListLayout.addView(stepsLayout);
			}
		}
	}

    public void showNotification(String type, String title, String message) {
        context = MainActivity.getInstance();

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

        intent.putExtra("type", type);

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

    /**
     * Function showGpsDialog()
     */
    public void showPosotionDialog() {
        new AlertDialog.Builder(mActivity)
                .setTitle("                 Location")
                .setMessage(
                        "Your Position is not known. Please enable your GPS position and go outside to get your real location")
                .setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                            }
                        }).show();
    }

    /**
     * Function getFirstDayOfService()
     * @param serviceId
     * @return
     *
     * Get the first day of a service
     */
	private long getFirstDayOfService(long serviceId) {
		List<DayServiceRel> daysId = dayServiceRelDao.queryBuilder()
				.where(Properties.Service.eq(serviceId))
				.orderAsc(Properties.Order).list();
		return daysId.get(0).getDay();
	}

    /**
     * ONCLICK serviceListener
     */
    private OnClickListener serviceListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ServiceFragment fg = new ServiceFragment();
            fg.setDayId(days.get(dayNo).getId());
            TextView tv = (TextView) v.findViewById(R.id.descriptionNoId);
            long i = Long.parseLong(tv.getText().toString());
            fg.setServiceId(i);
            fg.setDescriptionNo(0);

			//mActivity.pushFragments("MAP_TAB", fg, mActivity.mStacks.get("MAP_TAB").lastElement(), true);

			FragmentTransaction trans = getFragmentManager().beginTransaction();

			trans.replace(R.id.root_fragment, fg);

			trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			trans.addToBackStack(null);

			trans.commit();
        }

    };


    /**
     * ONCLICK listener
     *
     * Go to day button listener
     */
	private OnClickListener listener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			DayFragment fg = new DayFragment();

			FragmentTransaction trans = getFragmentManager().beginTransaction();

			trans.replace(R.id.root_fragment, fg);

			trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			trans.addToBackStack(null);

			trans.commit();
		}
	};


    /**
     * Class StepDescriptionClickListener
     *
     * Step description listener: shows the step description by clicking on the image
     */
	private class StepDescriptionClickListener implements OnClickListener {

		Step step;

        /**
         * Function StepDescriptionClickListener()
         * @param step
         */
		public StepDescriptionClickListener(Step step) {
			this.step = step;
		}



        /**
         * Function onClick()
         * @param arg0
         */
		@Override
		public void onClick(View arg0) {
			InfoFragment fg = new InfoFragment();
			fg.setName(step.getName());
			fg.setDetails(step.getDetails());
			fg.setDescriptionNo(0);

			FragmentTransaction trans = getFragmentManager().beginTransaction();

			trans.replace(R.id.root_fragment, fg);

			trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			trans.addToBackStack(null);

			trans.commit();
			//mActivity.pushFragments("MYTRIP_TAB", fg, mActivity.mStacks.get("MYTRIP_TAB").lastElement(), true);
		}

	}


    /**
     * Function activateAlternativeActivity()
     * @param id
     *
     * Public method that activates the alternative activity indicated by the id
     */
	public void activateAlternativeActivity(long id) {

 		Service s = serviceDao.load(id);
 		s.setAvailable(false);
 		serviceDao.update(s);
        loadTripSummary();

        if (s.getAlternativeServices().size()>0) {

            boolean activated = false;
            Service al = null;

            for (Service a : s.getAlternativeServices()) {
                if (a.getActivated()){
                    activated = true;
                    al = a;
                    break;
                }
            }

            if (!activated)
                al = s.getAlternativeServices().get(0);
            MapFragment mapFragment = (MapFragment) mActivity.mStacks.get("MAP_TAB").firstElement();
            mapFragment.updateDayServices((int)getFirstDayOfService(s.getId()), s.getId(), al.getId());

        }
 	}


    /**
     * Function chooseAlternativeActivity()
     * @param serviceId
     * @param alternativeId
     *
     * Public method that changes the selection of an alternative activity
     */
	public void chooseAlternativeActivity(long serviceId, long alternativeId) {

		Service s = serviceDao.load(serviceId);
		s.setAvailable(false);
		for (Service a : s.getAlternativeServices()) {
			if (a.getId() == alternativeId)
				a.setActivated(true);
			else
				a.setActivated(false);
			a.update();
		}
		serviceDao.update(s);
		loadTripSummary();

	}

	/**
	 * Class ExcursionDescriptionClickListener
	 *
	 * Excursion listener: shows the excursion description by clicking on the image
	 */
	private class ExcursionDescriptionClickListener implements OnClickListener {

		Excursion excursion;

		/**
		 * Function ExcursionDescriptionClickListener()
		 * @param excursion
		 */
		public ExcursionDescriptionClickListener(Excursion excursion) {
			this.excursion = excursion;
		}



		/**
		 * Function onClick()
		 * @param arg0
		 */
		@Override
		public void onClick(View arg0) {
			InfoFragment fg = new InfoFragment();
			fg.setName(excursion.getName());
			List<Detail> l = new ArrayList<Detail>();
			Detail d = new Detail();
			d.setFulldescr(excursion.getDescription());
			d.setPicture(excursion.getIcon());
			l.add(d);
			fg.setDetails(l);
			fg.setDescriptionNo(0);

			FragmentTransaction trans = getFragmentManager().beginTransaction();

			trans.replace(R.id.root_fragment, fg);

			trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			trans.addToBackStack(null);

			trans.commit();
			//mActivity.pushFragments("MYTRIP_TAB", fg, mActivity.mStacks.get("MYTRIP_TAB").lastElement(), true);
		}

	}

    /**
     * Class ServiceDescriptionClickListener
     *
     * Service description listener: shows the service description by clicking on the arrow image
     */
    private class ServiceDescriptionClickListener implements OnClickListener {

        Long id;
        /**
         * Function ServiceDescriptionClickListener()
         * @param id
         */
        public ServiceDescriptionClickListener(Long id) {
            this.id = id;
        }

        /**
         * Function onClick()
         * @param arg0
         */
        @Override
        public void onClick(View arg0) {
            ServiceFragment fg = new ServiceFragment();
            fg.setServiceId(id);
            fg.setDescriptionNo(0);

			FragmentTransaction trans = getFragmentManager().beginTransaction();

			trans.replace(R.id.root_fragment, fg);

			trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			trans.addToBackStack(null);

			trans.commit();
            //mActivity.pushFragments("MYTRIP_TAB", fg, mActivity.mStacks.get("MYTRIP_TAB").lastElement(), true);
        }

    }



    /**
     * Class ServiceDescriptionTouchListener
     *
     * Service description listener: shows the service description by clicking on the arrow image
     */
    private class ServiceDescriptionTouchListener implements View.OnTouchListener {

        Long id;
        MotionEvent m;
        /**
         * Function ServiceDescriptionTouchListener()
         * @param id
         */
        public ServiceDescriptionTouchListener(Long id) {
            this.id = id;
            this.m = m;
        }

        /**
         * Function onTouch()
         * @param arg0
         */
        @Override
        public boolean onTouch(View arg0, MotionEvent m) {
            float lastY =0;
            switch(m.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    arg0.setBackgroundColor(Color.GRAY);
                    lastY = m.getY();
                    break;
                case MotionEvent.ACTION_UP:
                    float a = Math.abs(lastY - m.getY());
                    if(a < 55){
                        arg0.setBackgroundColor(Color.TRANSPARENT);
                        arg0.setBackgroundColor(Color.TRANSPARENT);
                        ServiceFragment fg = new ServiceFragment();
                        fg.setServiceId(id);
                        fg.setDescriptionNo(0);
                        //mActivity.pushFragments("MYTRIP_TAB", fg, mActivity.mStacks.get("MYTRIP_TAB").lastElement(), true);

						FragmentTransaction trans = getFragmentManager().beginTransaction();

						trans.replace(R.id.root_fragment, fg);

						trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
						trans.addToBackStack(null);

						trans.commit();
                    }
                    break;
                case MotionEvent.ACTION_MOVE:
                    float abs = Math.abs(lastY - m.getY());
                    if(abs > 20)
                        arg0.setBackgroundColor(Color.TRANSPARENT);

                    break;
            }
            return true;
        }

    }

}