package com.beem.project.beem.ui;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.beem.project.beem.BeemService;
import com.beem.project.beem.R;
import com.beem.project.beem.service.aidl.IXmppFacade;
import com.beem.project.beem.utils.BeemBroadcastReceiver;
import com.beem.project.beem.utils.Status;

/**
 * This Activity is used to change the status.
 * @author nikita
 */
public class ChangeStatus extends Activity {

    private static final Intent SERVICE_INTENT = new Intent();
    static {
	SERVICE_INTENT.setComponent(new ComponentName("com.beem.project.beem", "com.beem.project.beem.BeemService"));
    }

    private static final int AVAILABLE_FOR_CHAT_IDX = 0;
    private static final int AVAILABLE_IDX = 1;
    private static final int BUSY_IDX = 2;
    private static final int AWAY_IDX = 3;
    private static final int UNAVAILABLE_IDX = 4;
    private static final int DISCONNECTED_IDX = 5;
    private TextView mStatusText;
    private Toast mToast;
    private Button mOk;
    private Button mClear;
    private Spinner mSpinner;

    private SharedPreferences mSettings;
    private ArrayAdapter<CharSequence> mAdapter;
    private IXmppFacade mXmppFacade;
    private final ServiceConnection mServConn = new BeemServiceConnection();
    private final OnClickListener mOnClickOk = new MyOnClickListener();
    private BeemBroadcastReceiver mReceiver;

    /**
     * Constructor.
     */
    public ChangeStatus() {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	setContentView(R.layout.changestatus);
	mStatusText = (TextView) findViewById(R.id.ChangeStatusText);
	mOk = (Button) findViewById(R.id.ChangeStatusOk);
	mClear = (Button) findViewById(R.id.ChangeStatusClear);
	mOk.setOnClickListener(mOnClickOk);
	mClear.setOnClickListener(mOnClickOk);
	mSettings = PreferenceManager.getDefaultSharedPreferences(this);

	mSpinner = (Spinner) findViewById(R.id.ChangeStatusSpinner);
	mAdapter = ArrayAdapter.createFromResource(this, R.array.status_types, android.R.layout.simple_spinner_item);
	mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	mSpinner.setAdapter(mAdapter);
	mToast = Toast.makeText(this, R.string.ChangeStatusOk, Toast.LENGTH_LONG);
	mReceiver = new BeemBroadcastReceiver(mServConn);
	mStatusText.setText(getPreferenceString(R.string.PreferenceStatusText));
	mSpinner.setSelection(getPreferenceStatusIndex());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onResume() {
	super.onResume();
	bindService(new Intent(this, BeemService.class), mServConn, BIND_AUTO_CREATE);
	mReceiver.setBinded();
	this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void onPause() {
	super.onPause();
	Log.d("TAG", "pause");
	this.unregisterReceiver(mReceiver);
	if (mReceiver.isBinded())
	    unbindService(mServConn);
    }

    /**
     * Return the status index from status the settings.
     * @return the status index from status the settings.
     */
    private int getPreferenceStatusIndex() {
	return mSettings.getInt(getString(R.string.PreferenceStatus), 0);
    }

    /**
     * Return the status text from status the settings.
     * @param id status text id.
     * @return the status text from status the settings.
     */
    private String getPreferenceString(int id) {
	return mSettings.getString(getString(id), "");
    }

    /**
     * convert status text to.
     * @param item selected item text.
     * @return item position in the array.
     */
    private int getStatusForService(String item) {
	switch (mAdapter.getPosition(item)) {
	    case ChangeStatus.DISCONNECTED_IDX:
		return Status.CONTACT_STATUS_DISCONNECT;
	    case ChangeStatus.AVAILABLE_FOR_CHAT_IDX:
		return Status.CONTACT_STATUS_AVAILABLE_FOR_CHAT;
	    case ChangeStatus.AVAILABLE_IDX:
		return Status.CONTACT_STATUS_AVAILABLE;
	    case ChangeStatus.AWAY_IDX:
		return Status.CONTACT_STATUS_AWAY;
	    case ChangeStatus.BUSY_IDX:
		return Status.CONTACT_STATUS_BUSY;
	    case ChangeStatus.UNAVAILABLE_IDX:
		return Status.CONTACT_STATUS_UNAVAILABLE;
	    default:
		return Status.CONTACT_STATUS_AVAILABLE;
	}
    }




    /**
     * connection to service.
     * @author nikita
     */
    private class BeemServiceConnection implements ServiceConnection {

	/**
	 * constructor.
	 */
	public BeemServiceConnection() {
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
	    mXmppFacade = IXmppFacade.Stub.asInterface(service);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onServiceDisconnected(ComponentName name) {
	    mXmppFacade = null;
	}
    }

    /**
     * User have clicked on ok.
     * @author nikita
     */
    private class MyOnClickListener implements OnClickListener {

	/**
	 * constructor.
	 */
	public MyOnClickListener() {
	}

	@Override
	public void onClick(View v) {
	    if (v == mOk) {
		if (!mStatusText.getText().toString().equals(getPreferenceString(R.string.PreferenceStatusText))
		    || getPreferenceStatusIndex() != mSpinner.getSelectedItemPosition()) {
		    String msg = mStatusText.getText().toString();
		    int status = getStatusForService((String) mSpinner.getSelectedItem());
		    Editor edit = mSettings.edit();
		    edit.putString(getString(R.string.PreferenceStatusText), msg);
		    edit.putInt(getString(R.string.PreferenceStatus), mSpinner.getSelectedItemPosition());
		    edit.commit();
		    if (status == Status.CONTACT_STATUS_DISCONNECT) {
			stopService(new Intent(ChangeStatus.this, BeemService.class));
			startActivity(new Intent(ChangeStatus.this, Login.class));
		    } else {
			try {
			    mXmppFacade.changeStatus(status, msg.toString());
			} catch (RemoteException e) {
			    e.printStackTrace();
			}
			mToast.show();
		    }
		}
		ChangeStatus.this.finish();
	    } else if (v == mClear) {
		mStatusText.setText(null);
	    }
	}
    }
}
