/**
 * 
 */
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.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.addc_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.addc_login).length() == 0) {
		valid = false;
	    } else {
		mLogin = getWidgetText(R.id.addc_login);
	    }
	    if (getWidgetText(R.id.addc_alias).length() == 0) {
		valid = false;
	    } else {
		mAlias = getWidgetText(R.id.addc_alias);
	    }
	    if (getWidgetText(R.id.addc_group).length() == 0) {
		valid = false;
	    } else {
		mGroup.add(getWidgetText(R.id.addc_group));
	    }
	    if (valid) {
		try {
		    mService.getRoster().addContact(mLogin, mAlias, (String[])mGroup.toArray(new String[mGroup.size()]));
		    Toast.makeText(AddContact.this, getString(R.string.AddCContactAdded),
	                    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, getString(R.string.AddCBadForm),
                    Toast.LENGTH_SHORT).show();
		setResult(RESULT_CANCELED);
	    }
	    
	}
    };
    
    private String getWidgetText(int id) {
	EditText widget = (EditText) this.findViewById(id);
	return widget.getText().toString();
    }
}
