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

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 String[] mGroup;
    private IXmppFacade mService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.addcontact);
	Button ok = (Button) findViewById(R.id.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.login).length() != 0) {
		Log.d(TAG, "login pas ok");
		valid = false;
	    } else {
		mLogin = getWidgetText(R.id.login);
	    }
	    if (getWidgetText(R.id.alias).length() != 0) {
		Log.d(TAG, "alias pas ok");
		valid = false;
	    } else {
		mAlias = getWidgetText(R.id.alias);
	    }
	    if (getWidgetText(R.id.group).length() != 0) {
		Log.d(TAG, "group pas ok");
		valid = false;
	    } else {
		mGroup[0] = getWidgetText(R.id.group);
	    }
	    if (valid) {
		try {
		    mService.getRoster().addContact(mLogin, mAlias, mGroup);
		    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();
    }
}
