/**
 * 
 */
package com.beem.project.beem.ui;

import java.util.ArrayList;
import java.util.List;

import com.beem.project.beem.BeemApplication;
import com.beem.project.beem.R;
import com.beem.project.beem.service.aidl.IXmppFacade;

import android.app.Activity;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * @author nikita
 *
 */
public class AddContact extends Activity {
    
    protected static final String TAG = "AddContact";
    private String mLogin;
    private String mAlias;
    private List<String> mGroup = new ArrayList<String>();
    private IXmppFacade mService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.addcontact);
	Button ok = (Button) findViewById(R.id.AC_ok);
	//mAccountManager = new AccountManager();
	ok.setOnClickListener(mOkListener);
	mService = BeemApplication.getApplication(this).getXmppFacade();
    }
    
    private OnClickListener mOkListener = new OnClickListener() {

	@Override
	public void onClick(View v) {
	    boolean valid = true;
	    if (getWidgetText(R.id.AC_login).length() == 0) {
		Log.d(TAG, "login pas ok");
		valid = false;
	    } else {
		mLogin = getWidgetText(R.id.AC_login);
	    }
	    if (getWidgetText(R.id.AC_alias).length() == 0) {
		Log.d(TAG, "alias pas ok");
		valid = false;
	    } else {
		mAlias = getWidgetText(R.id.AC_alias);
	    }
	    if (getWidgetText(R.id.AC_group).length() == 0) {
		Log.d(TAG, "group pas ok");
		valid = false;
	    } else {
		mGroup.add(getWidgetText(R.id.AC_group));
	    }
	    if (valid) {
		try {
		    mService.getRoster().addContact(mLogin, mAlias, (String[])mGroup.toArray(new String[mGroup.size()]));
		    Toast.makeText(AddContact.this, "Contact added",
	                    Toast.LENGTH_SHORT).show();
		    finish();
		} catch (RemoteException e) {
		    Toast.makeText(AddContact.this, e.getMessage(),
	                    Toast.LENGTH_SHORT).show();
		    e.printStackTrace();
		}
		setResult(RESULT_OK);
	    } else {
		Toast.makeText(AddContact.this, "Bad form",
                    Toast.LENGTH_SHORT).show();
		setResult(RESULT_CANCELED);
	    }
	    
	}
    };
    
    private String getWidgetText(int id) {
	EditText widget = (EditText) this.findViewById(id);
	return widget.getText().toString();
    }
}
