package com.beem.project.beem.ui;

import java.util.ArrayList;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import com.beem.project.beem.BeemApplication;
import com.beem.project.beem.R;
import com.beem.project.beem.service.Contact;
import com.beem.project.beem.service.Message;
import com.beem.project.beem.service.aidl.IChat;
import com.beem.project.beem.service.aidl.IChatManager;
import com.beem.project.beem.service.aidl.IChatManagerListener;
import com.beem.project.beem.service.aidl.IMessageListener;
import com.beem.project.beem.service.aidl.IXmppFacade;

/**
 * This activity class provides the view for instant messaging
 *         after selecting a correspondant.
 * @author barbu 
 */

public class SendIM extends Activity implements OnClickListener,
	OnKeyListener {
    private EditText mToSend;
    private ArrayList<String> mMessages = new ArrayList<String>();
    //private ArrayAdapter<String> mAdapter;
    private SendIMDialogSmiley mSmyDialog;
    private SharedPreferences mSet;
    private SharedPreferences mGlobalSettings;
    private BeemApplication mBeemApplication;
    private Handler mHandler;
    private IXmppFacade mService = null;
    private Contact mContact;
    private IChatManager mChatManager;
    private IChatManagerListener mChatManagerListener;
    private IMessageListener mMessageListener;
    private IChat mChat;
    private Drawable mAvatar;
    private TextView mText;
    private TextView mLogin;
    private ScrollView mScrolling;
    private boolean mSpeak;

    /**
     * Constructor.
     */
    public SendIM() {
	super();
    }

    /**
     * Overload of onCreate() Activity inherited function
     */
    @Override
    public void onCreate(Bundle saveBundle) {
	super.onCreate(saveBundle);
	setTheme(R.style.customtheme_contactList);
	mHandler = new Handler();
	mChatManagerListener = new OnChatListener();
	mMessageListener = new OnMessageListener();
	mBeemApplication = BeemApplication.getApplication(this);
	setContentView(R.layout.sendim);
	mToSend = (EditText) findViewById(R.id.userText);
	mSet = getSharedPreferences("lol", MODE_PRIVATE);
	mSmyDialog = new SendIMDialogSmiley(this, mSet);
	mGlobalSettings = getSharedPreferences(
		getString(R.string.PreferenceFileName), MODE_PRIVATE);
	/*mAdapter = new ArrayAdapter<String>(this, R.layout.messagelist,
		mMessages);
	setListAdapter(mAdapter);*/

	mToSend.setOnClickListener(this);
	mToSend.setOnKeyListener(this);
	mLogin = (TextView) findViewById(R.id.sendimlogin);
	mText = (TextView) findViewById(R.id.sendimlist);
	mScrolling = (ScrollView) findViewById(R.id.sendimscroll);
    }
    
    private void setViewHeader()
    {
	String status = mContact.getMsgState();
	if (status == null)
	    status = getString(R.string.SendIMNoStatusSet);
	else
	    status = mContact.getMsgState();
	mLogin.setText(mContact.getJID() + "\n" + status);
    }

    @Override
    public void onStart() {
	super.onStart();
	//TODO cancel the notification if any
	if (mContact == null)
	    mContact = getIntent().getParcelableExtra("contact");
	setViewHeader();
	mBeemApplication.startBeemService();
	mService = mBeemApplication.getXmppFacade();
	try {
	    mChatManager = mService.getChatManager();
	    mChatManager.addChatCreationListener(mChatManagerListener);
	    mChat = mChatManager.createChat(mContact, mMessageListener);
	    String text = mChat.getLastMessages();
	    if (! "".equals(text)) {
		mText.append(text);
		mChat.clearLastMessages(); 
	    }
	} catch (RemoteException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }

    @Override
    protected void onDestroy() {
	super.onDestroy();
	try {
	    mChatManager.removeChatCreationListener(mChatManagerListener);
	    mChatManager.destroyChat(mChat);
	} catch (RemoteException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }
    
    /**
     * Abstract method inherited from OnClickListener
     */
    public void onClick(View view) {
	sendText();
    }

    /**
     * This method send a message to the server over the XMPP connection and
     * display it on activity view TODO : Exception si la connexion se coupe
     * pendant la conversation
     */
    private void sendText() {
	if (mSpeak)
	    mSpeak = false;
	String text = mToSend.getText().toString();
	String from = mGlobalSettings.getString(
		getString(R.string.PreferenceJID), "You");
	if (!text.equals("")) {
	    Message msg = new Message(mContact.getJID(), Message.MSG_TYPE_CHAT);
	    msg.setBody(text);
	    try {
		mChat.sendMessage(msg);
	    } catch (RemoteException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	    //mAdapter.add(from + getString(R.string.SendIMSays) + text);
	    if (!mSpeak)
		mText.append(from + getString(R.string.SendIMSays) + text + "\n");
	    else
		mText.append(text + "\n");
	    mToSend.setText(null);
	    mScrolling.fullScroll(ScrollView.FOCUS_DOWN);
	    mToSend.requestFocus();
	    mSpeak = true;
	}
    }

    /**
     * Abstract method inherited from OnKeyListener
     */
    public boolean onKey(View v, int keyCode, KeyEvent event) {
	if (event.getAction() == KeyEvent.ACTION_DOWN) {
	    switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_CENTER:
		case KeyEvent.KEYCODE_ENTER:
		    sendText();
		    return true;
	    }
	}
	return false;
    }

    /**
     * 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.sendimmenu, menu);
	return true;
    }

    @Override
    public final boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
	    case R.id.sendim_smiley:
		mSmyDialog.show();
		return true;
	    default:
		return false;
	}
    }

    private class OnChatListener extends IChatManagerListener.Stub {

	@Override
	public void chatCreated(IChat chat, boolean locally)
		throws RemoteException {
	    Log.i("LOG", "chatCreated");

	}

    }

    private class OnMessageListener extends IMessageListener.Stub {

	@Override
	public void processMessage(IChat chat, Message msg)
		throws RemoteException {
	    Log.i("LOG", "processMessage");
	    /*mAdapter.add(mContact.getJID() + " "
		    + getString(R.string.SendIMSays) + msg.getBody());*/
	    if(chat!= mChat)
		return;
	    
	    final Message m = msg;
	    mHandler.post(new Runnable() {
	    
	        @Override
	        public void run() {
	            if (m.getBody() != null)
	            {
	        	if (!mSpeak)
	        	    mText.append(m.getBody() + "\n");
	        	else
	        	    mText.append(mContact.getJID() + " "
				    + getString(R.string.SendIMSays) + m.getBody() + "\n");
	        	mSpeak = false;
	        	mScrolling.fullScroll(ScrollView.FOCUS_DOWN);
	        	mToSend.requestFocus();
	            }
	        }
	    });
	}
    }
}
