package com.espritmobile.sim.restocheck.activities;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import org.w3c.dom.Text;

import com.espritmobile.sim.restocheck.R;
import com.espritmobile.sim.restocheck.entities.Element;
import com.espritmobile.sim.restocheck.entities.Person;
import com.espritmobile.sim.restocheck.facebook.FriendPickerApplication;
import com.espritmobile.sim.restocheck.facebook.PickFriendsActivity;
import com.espritmobile.sim.restocheck.utils.Utils;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.Session.NewPermissionsRequest;
import com.facebook.model.GraphUser;
import com.gc.materialdesign.views.ButtonRectangle;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.opengl.Visibility;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class PersoActivity extends Activity {

	TextView titre, bill, billPers, elem,currency,currencypers;
	TextView res;
	EditText name, part;
	ButtonRectangle next, addElement;
	int min = 1;
	double currentPart;
	double totale = 0.0;
	List<Element> elements;
	String montant = "0.00";
	String element = "";
	// FACEBOOK
	private static final List<String> PERMISSIONS = new ArrayList<String>() {
		{
			add("user_friends");
			add("public_profile");
		}
	};
	private static final int PICK_FRIENDS_ACTIVITY = 1;
	private ButtonRectangle pickFriendsButton;
	private UiLifecycleHelper lifecycleHelper;
	boolean pickFriendsWhenSessionOpened;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_perso);
		currency = (TextView) findViewById(R.id.currency);
		currency.setText(Utils.currency);
		currencypers = (TextView) findViewById(R.id.currencypers);
		currencypers.setText(Utils.currency);
		// FACEBOOK
		pickFriendsButton = (ButtonRectangle) findViewById(R.id.pickFriendsButton);
		pickFriendsButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				onClickPickFriends();
			}
		});

		lifecycleHelper = new UiLifecycleHelper(this,
				new Session.StatusCallback() {
					@Override
					public void call(Session session, SessionState state,
							Exception exception) {
						onSessionStateChanged(session, state, exception);
					}
				});
		lifecycleHelper.onCreate(savedInstanceState);
		ensureOpenSession();
		// FACEBOOK
		elements = new ArrayList<Element>();
		Toast.makeText(getApplicationContext(),
				Utils.persons.size() + " et " + (Utils.count),
				Toast.LENGTH_LONG).show();
		titre = (TextView) findViewById(R.id.titre);
		bill = (TextView) findViewById(R.id.bill);
		billPers = (TextView) findViewById(R.id.billPers);
		name = (EditText) findViewById(R.id.txtName);
		addElement = (ButtonRectangle) findViewById(R.id.addElement);
		elem = (TextView) findViewById(R.id.element);
		elem.setText(elem.getText() + " 0");
		next = (ButtonRectangle) findViewById(R.id.next);
		bill.setText(Utils.totale + "");
		min = Utils.persons.size() + 1;
		titre.setText(titre.getText() + "" + min+ " :");
		next.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (name.getText().length() != 0) {
					if ((Utils.persons.size() + 1 != Utils.count)
							&& (elements.size() != 0)) {
						Utils.totale += Double.parseDouble(currentPart + "");
						Person p = new Person();
						p.setName(name.getText().toString());
						p.setElements(elements);
						p.setPart(currentPart);
						p.setColor(Utils.colors[Utils.persons.size()]);
						Utils.persons.add(p);
						Utils.price = Utils.totale + "";
						Log.i("TAG", "Utilse.price : " + Utils.price);
						Log.i("TAG", "Utilse.totale : " + Utils.totale + "");
						Intent i = new Intent(getApplicationContext(),
								PersoActivity.class);
						startActivity(i);
						overridePendingTransition(android.R.anim.fade_in,
								android.R.anim.fade_in);
					} else {
						Utils.totale += Double.parseDouble(currentPart + "");
						Person p = new Person();
						p.setName(name.getText().toString());
						p.setElements(elements);
						p.setPart(currentPart);
						p.setColor(Utils.colors[Utils.persons.size()]);
						Utils.persons.add(p);
						Utils.price = Utils.totale + "";

						Log.i("TAG", "Utilse.price : " + Utils.price);
						Log.i("TAG", "Utilse.totale : " + Utils.totale + "");
						Intent i = new Intent(getApplicationContext(),
								PersoResultActivity.class);
						startActivity(i);
						overridePendingTransition(R.anim.slide_in_right,
								R.anim.slide_out_left);

					}
				} else
					Toast.makeText(getApplicationContext(),
							"Veuillez saisire un nom", Toast.LENGTH_LONG)
							.show();
			}
		});
		addElement.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (name.getText().length() != 0) {
					afficherElementDialog();
					name.setFocusable(false);
				} else
					Toast.makeText(getApplicationContext(),
							"Veuillez saisire un nom", Toast.LENGTH_LONG)
							.show();
			}
		});
	}

	private void afficherElementDialog() {
		final Dialog element_dialog = new Dialog(this);
		element_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		element_dialog.setContentView(R.layout.element_dialog);

		ButtonRectangle cancel, un, deux, trois, quattre, cinq, six, sept, huit, neuf, zero, back, dot;
		final Button platp;
		final Button dessert;
		final Button boisson;
		final RelativeLayout name;
		final RelativeLayout calc;
		final Element e = new Element();
		final ButtonRectangle next = (ButtonRectangle) element_dialog
				.findViewById(R.id.next);
		final Button entre;
		entre = (Button) element_dialog.findViewById(R.id.entre);
		platp = (Button) element_dialog.findViewById(R.id.platp);
		boisson = (Button) element_dialog.findViewById(R.id.boisson);
		dessert = (Button) element_dialog.findViewById(R.id.dessert);
		name = (RelativeLayout) element_dialog.findViewById(R.id.name);
		calc = (RelativeLayout) element_dialog.findViewById(R.id.calc);
		res = (TextView) element_dialog.findViewById(R.id.bill);
		montant = "";
		entre.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				element = entre.getText()+"";
				e.setName(element);
				name.setVisibility(View.GONE);
				calc.setVisibility(View.VISIBLE);
			}
		});

		platp.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				element = platp.getText()+"";
				e.setName(element);
				name.setVisibility(View.GONE);
				calc.setVisibility(View.VISIBLE);
			}
		});
		dessert.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				element = dessert.getText()+"";
				e.setName(element);
				name.setVisibility(View.GONE);
				calc.setVisibility(View.VISIBLE);
			}
		});
		boisson.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				element = boisson.getText()+"";
				e.setName(element);
				name.setVisibility(View.GONE);
				calc.setVisibility(View.VISIBLE);
			}
		});
		/*
		 * final EditText txtName = (EditText) element_dialog
		 * .findViewById(R.id.txtPlat);
		 */

		un = (ButtonRectangle) element_dialog.findViewById(R.id.un);
		un.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (montant.length() <= 6) {
					montant += "1";
					res.setText(montant);
				}
			}
		});
		deux = (ButtonRectangle) element_dialog.findViewById(R.id.deux);
		deux.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (montant.length() <= 6) {
					montant += "2";
					res.setText(montant);
				}
			}
		});
		trois = (ButtonRectangle) element_dialog.findViewById(R.id.trois);
		trois.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (montant.length() <= 6) {
					montant += "3";
					res.setText(montant);
				}
			}
		});
		quattre = (ButtonRectangle) element_dialog.findViewById(R.id.quattre);
		quattre.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (montant.length() <= 6) {
					montant += "4";
					res.setText(montant);
				}
			}
		});
		cinq = (ButtonRectangle) element_dialog.findViewById(R.id.cinq);
		cinq.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (montant.length() <= 6) {
					montant += "5";
					res.setText(montant);
				}
			}
		});
		six = (ButtonRectangle) element_dialog.findViewById(R.id.six);
		six.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (montant.length() <= 6) {
					montant += "6";
					res.setText(montant);
				}
			}
		});
		sept = (ButtonRectangle) element_dialog.findViewById(R.id.sept);
		sept.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (montant.length() <= 6) {
					montant += "7";
					res.setText(montant);
				}
			}
		});
		huit = (ButtonRectangle) element_dialog.findViewById(R.id.huit);
		huit.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (montant.length() <= 6) {
					montant += "8";
					res.setText(montant);
				}
			}
		});
		neuf = (ButtonRectangle) element_dialog.findViewById(R.id.neuf);
		neuf.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (montant.length() <= 6) {
					montant += "9";
					res.setText(montant);
				}
			}
		});
		zero = (ButtonRectangle) element_dialog.findViewById(R.id.zero);
		zero.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (montant.length() <= 6) {
					if (montant.length() != 0)
						if (montant.charAt(0) != '0') {
							montant += "0";
							res.setText(montant);
						}
				}
			}
		});
		back = (ButtonRectangle) element_dialog.findViewById(R.id.back);
		back.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (montant.length() > 0) {
					montant = montant.substring(0, montant.length() - 1);
					res.setText(montant);
				}
			}
		});
		dot = (ButtonRectangle) element_dialog.findViewById(R.id.dot);
		dot.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (montant.length() <= 6) {
					if (!montant.contains("."))
						if (montant.length() != 0) {
							montant += ".";
							res.setText(montant);
						}
				}
			}
		});
		next.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (name.getVisibility() == View.VISIBLE) {

					if (element.length() != 0) {
						e.setName(element);
						name.setVisibility(View.GONE);
						calc.setVisibility(View.VISIBLE);
					} else
						Toast.makeText(getApplicationContext(),
								"Veuillez choisir un type d'element",
								Toast.LENGTH_LONG).show();
				} else {
					if (element.length() != 0) {
						if (montant.length() != 0) {
							e.setPrice(Double.parseDouble(montant));
							totale += Double.parseDouble(montant);
							currentPart = totale;
							billPers.setText(totale + "");
							elements.add(e);
							elem.setText(elem.getText().subSequence(0,
									elem.getText().length() - 1)
									+ " " + elements.size());
							element_dialog.dismiss();
						} else {
							Toast.makeText(getApplicationContext(),
									"Veuillez saisire un montant",
									Toast.LENGTH_LONG).show();
						}
					} else
						Toast.makeText(getApplicationContext(),
								"Veuillez choisir un type d'element",
								Toast.LENGTH_LONG).show();

				}
			}

		});
		cancel = (ButtonRectangle) element_dialog.findViewById(R.id.cancel);
		cancel.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (name.getVisibility() == View.VISIBLE) {
					element_dialog.dismiss();
				} else {
					montant = "";
					res.setText("0.0");
					calc.setVisibility(View.INVISIBLE);
					name.setVisibility(View.VISIBLE);
				}
			}
		});

		element_dialog.setCanceledOnTouchOutside(true);
		element_dialog.show();

	}

	// FACEBOOK
	@Override
	protected void onStart() {
		super.onStart();

		// Update the display every time we are started.
		displaySelectedFriends(RESULT_OK);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PICK_FRIENDS_ACTIVITY:
			displaySelectedFriends(resultCode);
			break;
		default:
			Session.getActiveSession().onActivityResult(this, requestCode,
					resultCode, data);
			break;
		}
	}

	private boolean ensureOpenSession() {
		if (Session.getActiveSession() == null
				|| !Session.getActiveSession().isOpened()) {
			Session.openActiveSession(this, true, PERMISSIONS,
					new Session.StatusCallback() {
						@Override
						public void call(Session session, SessionState state,
								Exception exception) {
							onSessionStateChanged(session, state, exception);
						}
					});
			return false;
		}
		return true;
	}

	private boolean sessionHasNecessaryPerms(Session session) {
		if (session != null && session.getPermissions() != null) {
			for (String requestedPerm : PERMISSIONS) {
				if (!session.getPermissions().contains(requestedPerm)) {
					return false;
				}
			}
			return true;
		}
		return false;
	}

	private List<String> getMissingPermissions(Session session) {
		List<String> missingPerms = new ArrayList<String>(PERMISSIONS);
		if (session != null && session.getPermissions() != null) {
			for (String requestedPerm : PERMISSIONS) {
				if (session.getPermissions().contains(requestedPerm)) {
					missingPerms.remove(requestedPerm);
				}
			}
		}
		return missingPerms;
	}

	private void onSessionStateChanged(final Session session,
			SessionState state, Exception exception) {
		if (state.isOpened() && !sessionHasNecessaryPerms(session)) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("In order to pick your friends you need to accept all the permissions on the following page.");
			builder.setPositiveButton("Ok",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							session.requestNewReadPermissions(new NewPermissionsRequest(
									PersoActivity.this,
									getMissingPermissions(session)));
						}
					});
			builder.setNegativeButton("Quitter",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					});
			builder.show();
		} else if (pickFriendsWhenSessionOpened && state.isOpened()) {
			pickFriendsWhenSessionOpened = false;

			startPickFriendsActivity();
		}
	}

	private void displaySelectedFriends(int resultCode) {
		String results = "";
		FriendPickerApplication application = (FriendPickerApplication) getApplication();
		Collection<GraphUser> selection = application.getSelectedUsers();
		if (selection != null && selection.size() > 0) {
			ArrayList<String> names = new ArrayList<String>();
			for (GraphUser user : selection) {
				names.add(user.getName());
			}
			results = TextUtils.join(", ", names);
		} else {
			results = "";
		}

		name.setText(results);
	}

	private void onClickPickFriends() {
		startPickFriendsActivity();
	}

	private void startPickFriendsActivity() {
		if (ensureOpenSession()) {
			Intent intent = new Intent(this, PickFriendsActivity.class);
			// Note: The following line is optional, as multi-select behavior is
			// the default for
			// FriendPickerFragment. It is here to demonstrate how parameters
			// could be passed to the
			// friend picker if single-select functionality was desired, or if a
			// different user ID was
			// desired (for instance, to see friends of a friend).
			PickFriendsActivity.populateParameters(intent, null, true, true);
			startActivityForResult(intent, PICK_FRIENDS_ACTIVITY);
		} else {
			pickFriendsWhenSessionOpened = true;
		}
	}

}