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

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

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;
    private boolean isOpen;
    private List<Message> mMessages;

    /**
     * Constructor.
     * @param chat The chat to adapt
     */
    public ChatAdapter(final Chat chat) {
	mLastMessages = new StringBuffer();
	mAdaptee = chat;
	mParticipant = new Contact(chat.getParticipant());
	mMessages = new LinkedList<Message>();
    }

    /**
     * {@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);
	    mMessages.add(message);
	} 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;
    }

    /**
     * @param isOpen the isOpen to set
     */
    @Override
    public void setOpen(boolean isOpen) {
	this.isOpen = isOpen;
    }

    /**
     * @return the isOpen
     */
    @Override
    public boolean isOpen() {
	return isOpen;
    }

    @Override
    public List<Message> getMessages() throws RemoteException {
	return Collections.unmodifiableList(mMessages);
    }

    void addMessage(Message msg) {
	if (mMessages.size() == 50)
	    mMessages.remove(0);
	mMessages.add(msg);
    }

}
