package com.beem.project.beem.ui;

import java.util.List;

import org.jivesoftware.smack.packet.Presence;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.TextView;
import android.widget.Toast;

import com.beem.project.beem.BeemService;
import com.beem.project.beem.R;
import com.beem.project.beem.service.Contact;
import com.beem.project.beem.service.PresenceAdapter;
import com.beem.project.beem.service.aidl.IRoster;
import com.beem.project.beem.service.aidl.IXmppFacade;
import com.beem.project.beem.utils.BeemBroadcastReceiver;

/**
 * This activity class provides the view for user infos after long click on a
 * correspondant.
 * 
 * @author marseille
 */
public class UserInfo extends Activity {

	private static final Intent SERVICE_INTENT = new Intent();
	private final ServiceConnection mServConn = new BeemServiceConnection();
	private TextView mTextAlias;
	private Gallery mGalleryGroups;
	private Contact mContact;
	private IXmppFacade mXmppFacade;
	private BeemBroadcastReceiver mReceiver;
	private String mJID;
	private IRoster mRoster;

	static {
		SERVICE_INTENT.setComponent(new ComponentName("com.beem.project.beem", "com.beem.project.beem.BeemService"));
	}

	/**
	 * Constructor.
	 */
	public UserInfo() {
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.userinfo);
		View v = (View) findViewById(R.id.userinfo_layout_alias);
		v.setOnClickListener(new AliasListener());
		v = findViewById(R.id.userinfo_layout_delete);
		v.setOnClickListener(new DeleteListener());
		v = findViewById(R.id.userinfo_layout_chg_group);
		v.setOnClickListener(new GroupListener());
		v = findViewById(R.id.userinfo_layout_re_suscription);
		v.setOnClickListener(new ResendListener());
		mTextAlias = (TextView) findViewById(R.id.userinfo_alias);
		mGalleryGroups = (Gallery) findViewById(R.id.userinfo_groups);
		mReceiver = new BeemBroadcastReceiver(mServConn);
		this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED));
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onResume() {
		super.onResume();
		bindService(new Intent(this, BeemService.class), mServConn, BIND_AUTO_CREATE);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onPause() {
		super.onPause();
		if (mReceiver.isBinded()) {
			unbindService(mServConn);
			mReceiver.setBinded(false);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(mReceiver);
	}

	/**
	 * Event simple click on layout alias.
	 */
	private class AliasListener implements View.OnClickListener {
		/**
		 * Constructor.
		 */
		public AliasListener() {
		}

		@Override
		public void onClick(View v) {
			Dialog d = new DialogAlias();
			d.show();
		}
	}

	/**
	 * Event simple click on layout group.
	 */
	private class GroupListener implements View.OnClickListener {
		/**
		 * Constructor.
		 */
		public GroupListener() {
		}

		@Override
		public void onClick(View v) {
			Intent i = new Intent(UserInfo.this, GroupList.class);
			i.putExtra("contact", mContact);
			startActivity(i);
		}

	}

	/**
	 * Create dialog alias.
	 */
	public class DialogAlias extends Dialog {

		/**
		 * Constructor.
		 */
		public DialogAlias() {
			super(UserInfo.this);
			setContentView(R.layout.contactdialogaliasdialog);
			setTitle(mContact.getJID());
			EditText nameText = (EditText) findViewById(R.id.CDAliasDialogName);
			if (mContact.getName().length() == 0)
				nameText.setText(mContact.getJID());
			else
				nameText.setText(mContact.getName());
			Button ok = (Button) findViewById(R.id.CDAliasDialogOk);
			ok.setOnClickListener(new ContactDialogAliasDialogOK());
		}

		/**
		 * Event click on the button OK.
		 */
		private class ContactDialogAliasDialogOK implements View.OnClickListener {

			/**
			 * Constructor.
			 */
			public ContactDialogAliasDialogOK() {
			}

			@Override
			public void onClick(View v) {
				try {
					EditText nameText = (EditText) findViewById(R.id.CDAliasDialogName);
					String name = nameText.getText().toString();
					if (name.length() == 0)
						name = mContact.getJID();
					mRoster.setContactName(mContact.getJID(), name);
					mContact.setName(name);
					mTextAlias.setText(name);

				} catch (RemoteException e) {
					e.printStackTrace();
				}
				dismiss();
			}
		}
	}

	/**
	 * Adapter group horizontal list.
	 */
	public class BeemGroups extends BaseAdapter {
		private Context mContext;
		private List<String> mListGroup;

		/**
		 * Constructor.
		 * 
		 * @param c
		 *            context activity.
		 * @param listGroup
		 *            the user group list.
		 */
		public BeemGroups(final Context c, final List<String> listGroup) {
			mContext = c;
			if (listGroup.size() == 0)
				listGroup.add(getString(R.string.contact_list_no_group));
			mListGroup = listGroup;
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public int getCount() {
			return mListGroup.size();
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public Object getItem(int position) {
			return position;
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public long getItemId(int position) {
			return position;
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView textView = new TextView(mContext);
			textView.setText(mListGroup.get(position));
			return textView;
		}

	}

	/**
	 * Event simple click on layout resend suscription.
	 */
	class ResendListener implements View.OnClickListener {

		/**
		 * Constructor.
		 */
		public ResendListener() {
		}

		@Override
		public void onClick(View v) {

			AlertDialog.Builder builder = new AlertDialog.Builder(UserInfo.this);
			builder.setMessage(UserInfo.this.getString(R.string.userinfo_sureresend)).setCancelable(false)
					.setPositiveButton(UserInfo.this.getString(R.string.userinfo_yes),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									Presence presencePacket = new Presence(Presence.Type.subscribe);
									presencePacket.setTo(mContact.getJID());
									try {
										mXmppFacade.sendPresencePacket(new PresenceAdapter(presencePacket));
									} catch (RemoteException e) {
										e.printStackTrace();
									}
									Toast.makeText(UserInfo.this, getString(R.string.userinfo_resend),
											Toast.LENGTH_SHORT).show();
								}
							}).setNegativeButton(UserInfo.this.getString(R.string.userinfo_no),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		}

	}

	/**
	 * Event simple click on layout delete.
	 */
	class DeleteListener implements View.OnClickListener {

		/**
		 * Constructor.
		 */
		public DeleteListener() {
		}

		@Override
		public void onClick(View v) {
			AlertDialog.Builder builder = new AlertDialog.Builder(UserInfo.this);
			builder.setMessage(UserInfo.this.getString(R.string.userinfo_sure2delete)).setCancelable(false)
					.setPositiveButton(UserInfo.this.getString(R.string.userinfo_yes),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									try {
										mRoster.deleteContact(mContact);
									} catch (RemoteException e) {
										e.printStackTrace();
									}
									finish();
								}
							}).setNegativeButton(UserInfo.this.getString(R.string.userinfo_no),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		}
	}

	/**
	 * The ServiceConnection used to connect to the Beem service.
	 */
	private class BeemServiceConnection implements ServiceConnection {

		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mXmppFacade = IXmppFacade.Stub.asInterface(service);
			mReceiver.setBinded(true);
			try {
				mRoster = mXmppFacade.getRoster();
				mJID = getIntent().getStringExtra("contact_contactdialog");
				mContact = mRoster.getContact(mJID);
				if (mContact.getName() != null)
					mTextAlias.setText(mContact.getName());
				else
					mTextAlias.setText(mContact.getJID());
				mGalleryGroups.setAdapter(new BeemGroups(UserInfo.this, mContact.getGroups()));
				setTitle(mJID);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mXmppFacade = null;
		}
	}
}
