package com.beem.project.beem.ui;

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

import com.beem.project.beem.R;

public class ContactListSettings extends Activity {

    public static final int CHANGE = 1;
    private SharedPreferences mSettings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.contactlistsettings);
	mSettings = getSharedPreferences(
		getString(R.string.PreferenceFileName), MODE_PRIVATE);
	showSettings();
	Button ok = (Button) findViewById(R.id.ok);
	ok.setOnClickListener(mOkListener);
    }

    private OnClickListener mOkListener = new OnClickListener() {
	public void onClick(View v) {
	    boolean b = false;
	    SharedPreferences.Editor editor = mSettings.edit();

	    if (isChanged(R.id.host, R.string.PreferenceHostKey)) {
		editor.putString(
			getString(R.string.PreferenceHostKey),
			getWidgetText(R.id.host));
		b = true;
	    }
	    if (isChanged(R.id.port, R.string.PreferencePortKey)) {
		editor.putString(
			getString(R.string.PreferencePortKey),
			getWidgetText(R.id.port));
		b = true;
	    }
	    if (isChanged(R.id.userid, R.string.PreferenceLoginKey)) {
		editor.putString(
			getString(R.string.PreferenceLoginKey),
			getWidgetText(R.id.userid));
		b = true;
	    }
	    if (isChanged(R.id.password, R.string.PreferencePasswordKey)) {
		editor.putString(
			getString(R.string.PreferencePasswordKey),
			getWidgetText(R.id.password));
		b = true;
	    }

	    if (b == true) {
		editor.commit();
		setResult(RESULT_OK);
	    } else
		setResult(RESULT_CANCELED);
	    finish();
	}
    };

    private boolean isChanged(int idEdit, int idPreference) {
	return (!getWidgetText(idEdit).equals(getPreferenceString(idPreference)));
    }

    private void showSettings() {
	EditText e = (EditText) findViewById(R.id.host);
	e.setText(getPreferenceString(R.string.PreferenceHostKey));
	e = (EditText) findViewById(R.id.port);
	e.setText(getPreferenceString(R.string.PreferencePortKey));
	e = (EditText) findViewById(R.id.userid);
	e.setText(getPreferenceString(R.string.PreferenceLoginKey));
	e = (EditText) findViewById(R.id.password);
	e.setText(getPreferenceString(R.string.PreferencePasswordKey));
    }

    private String getWidgetText(int id) {
	EditText widget = (EditText) this.findViewById(id);
	return widget.getText().toString();
    }

    private String getPreferenceString(int id) {
	return mSettings.getString(getString(id), "");
    }

}
