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

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterGroup;
import org.jivesoftware.smack.XMPPException;

import android.os.RemoteException;

/**
 * This class implement a Roster adapter for BEEM.
 * @author darisk
 */
public class RosterAdapter extends com.beem.project.beem.service.aidl.IRoster.Stub {

    private Roster mAdaptee;
    private Map<String, Contact> mContacts = new HashMap<String, Contact>();

    /**
     * Constructor.
     * @param roster the roster to adapt
     */
    public RosterAdapter(final Roster roster) {
	mAdaptee = roster;
	for (RosterEntry entry : roster.getEntries()) {
	    String user = entry.getUser();
	    mContacts.put(user, new Contact(user));
	}
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void createGroup(String groupname) throws RemoteException {
	// TODO Auto-generated method stub
	mAdaptee.createGroup(groupname);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Contact addContact(String user, String name, String[] groups) throws RemoteException {
	try {
	    mAdaptee.createEntry(user, name, groups);
	    Contact res = new Contact(user);
	    mContacts.put(user, res);
	    return res;
	} catch (XMPPException e) {
	    return null;
	}
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void deleteContact(Contact contact) throws RemoteException {
	// TODO Auto-generated method stub

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Contact getContact(String jid) throws RemoteException {
	return mContacts.get(jid);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Contact> getContactList() throws RemoteException {
	List<Contact> res = new ArrayList<Contact>();
	res.addAll(mContacts.values());
	return res;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<String> getGroupsNames() throws RemoteException {
	Collection<RosterGroup> groups = mAdaptee.getGroups();
	ArrayList<String> result = new ArrayList<String>(groups.size());
	for (RosterGroup rosterGroup : groups) {
	    result.add(rosterGroup.getName());
	}
	return result;
    }

}
