package com.beem.project.beem.ui;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.ComponentName;
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.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.TextView;

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.aidl.IRoster;
import com.beem.project.beem.service.aidl.IXmppFacade;
import com.beem.project.beem.utils.BeemBroadcastReceiver;

/**
 * That activity permit to manage user groups.
 * @author nikita
 */
public class GroupList extends ListActivity {

    private static final Intent SERVICE_INTENT = new Intent();

    private final ServiceConnection mServConn = new BeemServiceConnection();
    private BeemBroadcastReceiver mReceiver;
    private IXmppFacade mXmppFacade;
    private IRoster mRoster;
    private String mJID;
    private ArrayAdapter<String> mGroups;
    private Contact mContact;
    private TextView mText;
    private final ArrayList<String> mStrings = new ArrayList<String>();

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

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.group_list);
	mReceiver = new BeemBroadcastReceiver(mServConn);
	mContact = getIntent().getParcelableExtra("contact");
	mJID = mContact.getJID();
	final ListView listView = getListView();

	listView.setItemsCanFocus(false);
	listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

	mText = (TextView) findViewById(R.id.GroupListText);
	mText.setOnKeyListener(new GroupListOnKeyListener());
    }

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

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

    /**
     * On group click listener.
     * @param l The ListView where the click happened
     * @param v The view that was clicked within the ListView
     * @param position The position of the view in the list
     * @param id The row id of the item that was clicked
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
	Log.d("GROUPLIST", "CLICK");
	CheckedTextView textView = (CheckedTextView) v;
	if (textView.isChecked()) {
	    try {
		mRoster.addContactToGroup(textView.getText().toString(), mJID);
	    } catch (RemoteException e) {
		e.printStackTrace();
	    }
	} else {
	    try {
		mRoster.removeContactFromGroup(textView.getText().toString(), mJID);
	    } catch (RemoteException e) {
		e.printStackTrace();
	    }
	}
    }

    /**
     * init activity lsit adapter.
     */
    private void setAdapter() {
	try {
	    for (String group : mRoster.getGroupsNames()) {
		mStrings.add(group);
	    }
	    mGroups = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, mStrings);
	    setListAdapter(mGroups);
	    mContact = mRoster.getContact(mJID);
	    for (String group : mContact.getGroups()) {
		getListView().setItemChecked(mGroups.getPosition(group), true);
	    }
	} catch (RemoteException e) {
	    e.printStackTrace();
	}
    }

    /**
     * GroupListOnKeyListener class.
     */
    private class GroupListOnKeyListener implements OnKeyListener {

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
	    if (event.getAction() == KeyEvent.ACTION_DOWN) {
		switch (keyCode) {
		    case KeyEvent.KEYCODE_DPAD_CENTER:
		    case KeyEvent.KEYCODE_ENTER:
			if (mText.getText().length() == 0)
			    return false;
			String groupname = mText.getText().toString();
			mGroups.add(groupname);
			mText.setText(null);
			try {
			    mRoster.createGroup(groupname);
			} catch (RemoteException e) {
			    e.printStackTrace();
			}
			return true;
		    default:
			return false;
		}
	    }
	    return false;
	}

    }

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

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

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
	    mXmppFacade = IXmppFacade.Stub.asInterface(service);
	    try {
		mRoster = mXmppFacade.getRoster();
		setAdapter();
	    } catch (RemoteException e) {
		e.printStackTrace();
	    }
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
	    mXmppFacade = null;
	    mRoster = null;
	}
    }

}
