/**
 * 
 */
package com.beem.project.beem.service;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPException;

import android.os.RemoteException;

import com.beem.project.beem.service.aidl.IChat;

/**
 * An adapter for smack's Chat class.
 * @author darisk
 */
public class ChatAdapter extends IChat.Stub {
    private Chat mAdaptee;
    private Contact mParticipant;
    private String mState;
    private StringBuffer mLastMessages;
 
    /**
     * Constructor.
     * @param chat The chat to adapt
     */
    public ChatAdapter(final Chat chat) {
	mLastMessages = new StringBuffer();
	mAdaptee = chat;
	mParticipant = new Contact(chat.getParticipant());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Contact getParticipant() throws RemoteException {
	return mParticipant;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void sendMessage(com.beem.project.beem.service.Message message) throws RemoteException {
	org.jivesoftware.smack.packet.Message send = new org.jivesoftware.smack.packet.Message();
	send.setTo(message.getTo());
	send.setBody(message.getBody());
	send.setThread(message.getThread());
	send.setSubject(message.getSubject());
	send.setType(org.jivesoftware.smack.packet.Message.Type.chat);
	// TODO gerer les messages contenant des XMPPError
	// send.set
	try {
	    mAdaptee.sendMessage(send);
	} catch (XMPPException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }

    @Override
    public String getState() throws RemoteException {
	return mState;
    }
    
    @Override
    public void setState(String state) throws RemoteException {
	mState = state;
    }

    public Chat getAdaptee() {
	return mAdaptee;
    }

    @Override
    public String getLastMessages() throws RemoteException {
	return mLastMessages.toString();
    }

    @Override
    public void addToLastMessages(String msg) throws RemoteException {
	mLastMessages.append(msg).append('\n');
    }

    @Override
    public void clearLastMessages() throws RemoteException {
	mLastMessages.delete(0, mLastMessages.length());
    }

}
