package com.beem.project.beem.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.beem.project.beem.BeemApplication;
import com.beem.project.beem.R;

/**
 * La principale activite to be continuous.
 */
public class Beem extends Activity {

    private SharedPreferences mSettings;
    private BeemDialogSettings mDialog;
    private Button mButton;
    private Handler mHandler;
    private BeemApplication mBeemApplication;

    /**
     * Default constructor.
     */
    public Beem() {
	super();
	mHandler = new Handler();
    }

    /**
     * Called when the activity is first created.
     * @param savedInstanceState
     *            previous state.
     */
    @Override
    public final void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	mBeemApplication = BeemApplication.getApplication(this);
	setContentView(R.layout.beem);
	mSettings = getSharedPreferences(
		getString(R.string.PreferenceFileName), MODE_PRIVATE);
	mDialog = new BeemDialogSettings(this, mSettings);

	mButton = (Button) findViewById(R.id.connection);
	mButton.setOnClickListener(new OnClickListener() {
	    @Override
	    public void onClick(View v) {
		if (mButton.getText() == getString(R.string.BeemCreateAccount))
		    mDialog.show();
		else
		    startActivity(new Intent(Beem.this, ContactList.class));	    
	    }
	});
	showJID();
    }

    /**
     * Callback for menu creation.
     * @param menu
     *            the menu created
     * @return true on success, false otherwise
     */
    @Override
    public final boolean onCreateOptionsMenu(Menu menu) {
	super.onCreateOptionsMenu(menu);
	MenuInflater inflater = getMenuInflater();
	inflater.inflate(R.menu.beemmenu, menu);
	return true;
    }

    /**
     * Callback for menu item selected.
     * @param item
     *            the item selected
     * @return true on success, false otherwise
     */
    @Override
    public final boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
	    case R.id.account_edit:
		mDialog.show();
		return true;
	    case R.id.account_about:
		return true;
	    default:
		return false;
	}
    }

    /**
     * Show jabber id in button.
     */
    public final void showJID() {
	String jid = mSettings.getString(
		getString(R.string.PreferenceLoginKey), "")
		+ "@"
		+ mSettings
			.getString(getString(R.string.PreferenceHostKey), "");
	if (jid.length() == 1)
	    jid = getString(R.string.BeemCreateAccount);
	mButton.setText(jid);
    }

}
