/*
 * ServiceFragment.java
 * Shows the service description
 */

package com.cc.infosur.mytrip;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.cc.infosur.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cc.infosur.greendao.DaoMaster;
import com.cc.infosur.greendao.DaoSession;
import com.cc.infosur.greendao.DayDao;
import com.cc.infosur.greendao.Detail;
import com.cc.infosur.greendao.Service;
import com.cc.infosur.greendao.ServiceDao;
import com.cc.infosur.greendao.Trip;
import com.cc.infosur.greendao.TripDao;
import com.cc.infosur.greendao.DaoMaster.DevOpenHelper;
import com.cc.infosur.main.MainActivity;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.method.ScrollingMovementMethod;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class ServiceFragment extends Fragment {

	//Buttons and textviews
	private ImageView goToDayButton;
	private TextView textDescription;
	private TextView textDay;
	private TextView textNameService;

	private ImageView imageDescription;
	private LinearLayout pageIndicatorLayout;

	private long dayId;
	private long serviceId;
	private int descriptionNo;
	private String name = "";
	private List<Detail> detail;
	private ArrayList<String> images;

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

	public MainActivity mActivity;

	private GestureDetector gestureDetector;
	View.OnTouchListener gestureListener;

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



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

        View V = inflater.inflate(R.layout.service, container, false);

		// Gesture detection
		gestureDetector = new GestureDetector(getActivity(),
				new MyGestureDetector());
		gestureListener = new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				return gestureDetector.onTouchEvent(event);
			}
		};

		V.setOnTouchListener(gestureListener);

		mActivity = (MainActivity) this.getActivity();

		// Get and set images and textviews
		pageIndicatorLayout = (LinearLayout) V.findViewById(R.id.pageIndicatorLayout);

		textDescription = (TextView) V.findViewById(R.id.textDescription);
		textDescription.setMovementMethod(new ScrollingMovementMethod());
		textDescription.setOnTouchListener(gestureListener);

		textDay = (TextView) V.findViewById(R.id.textDay);
		textNameService = (TextView) V.findViewById(R.id.textNameService);

		imageDescription = (ImageView) V.findViewById(R.id.sentImageView);
        //imageDescription.setOnClickListener(imageListener);

		goToDayButton = (ImageView) V.findViewById(R.id.goToDayButton);
		goToDayButton.setOnClickListener(goToDayListener);

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

		SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, d MMMM");

        textDay.setText("EVENEMENT");

		Service service = serviceDao.load(serviceId);
		textNameService.setText(service.getName());

		detail = service.getDetails();

		WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);
		
		showPageIndicatorDots();

		initializeDescription();

		imageDescription.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Log.e("CLICK", "IMAGE "+descriptionNo);
				FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
				ImageFullScreenFragment imageFullScreenFragment = new ImageFullScreenFragment();
				imageFullScreenFragment.setPicture(detail.get(descriptionNo).getPicture());

				ft.replace(R.id.root_fragment, imageFullScreenFragment);
				ft.addToBackStack(null);
				ft.commit();
			}
		});

		return V;
	}


    /**
     * Onclick goToDayListener
     *
     * Go back to day listener
     */
	private OnClickListener goToDayListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			//mActivity.popFragments();
			System.out.print("prev --------------------------------");
			getFragmentManager().popBackStack();
		}
	};


	// Public methods to prepare the service description from the day fragment
	public void setDayId(long n) {
		this.dayId = n;
	}

	public long getDayId() {
		return this.dayId;
	}

	public void setServiceId(long n) {
		this.serviceId = n;
	}

	public long getServiceId() {
		return this.serviceId;
	}

	public void setDescriptionNo(int n) {
		this.descriptionNo = n;
	}

	public int getDescriptionNo() {
		return this.descriptionNo;
	}



    /**
     * Function initializeDescription()
     *
     * Set the description, images and page indicator dots of the service
     */
	private void initializeDescription() {

		showPageIndicatorDots();

		textDescription.setText(detail.get(descriptionNo).getFulldescr());

		Bitmap bmp = BitmapFactory
				.decodeByteArray(detail.get(descriptionNo).getPicture(), 0,
						detail.get(descriptionNo).getPicture().length);
		imageDescription.setImageBitmap(bmp);
	}


    /**
     * Function showPageIndicatorDots()
     *
     * Method to add the page indicator dots
     */
	private void showPageIndicatorDots() {

		pageIndicatorLayout.removeAllViews();
		ImageView iv;
		for (int i = 0; i < detail.size(); i++) {
			iv = new ImageView(getActivity());
			if (i == descriptionNo)
				iv.setImageDrawable(getResources().getDrawable(
						R.drawable.dot_green));
			else
				iv.setImageDrawable(getResources().getDrawable(
						R.drawable.dot_grey));
			pageIndicatorLayout.addView(iv);
		}

	}



    /**
     * Class MyGestureDetector
     *
     * GestureListener that detects swipe right and left and changes the description page
     */
	private class MyGestureDetector extends SimpleOnGestureListener {

		private static final int SWIPE_MIN_DISTANCE = 120;
		private static final int SWIPE_MAX_OFF_PATH = 250;
		private static final int SWIPE_THRESHOLD_VELOCITY = 200;


        /**
         * Function onFling()
         * @param e1
         * @param e2
         * @param velocityX
         * @param velocityY
         * @return
         */
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			try {
				if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
					return false;
				// right to left swipe
				if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					Log.i("DOTS", "SWIPE RIGHT");
					if (descriptionNo < detail.size() - 1) {
						setDescriptionNo(getDescriptionNo() + 1);
						initializeDescription();
					}
				} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					if (descriptionNo > 0) {
						setDescriptionNo(getDescriptionNo() - 1);
						initializeDescription();
					}
				}
			} catch (Exception e) {
				// nothing
			}
			return false;
		}


        /**
         * Function onDown()
         * @param e
         * @return
         */
		@Override
		public boolean onDown(MotionEvent e) {
			return true;
		}
	}

}
