package be.ac.ulb.code.wit.resources.serializers.atom;

import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.util.Constants;

import be.ac.ulb.code.wit.contacts.Contacts;
import be.ac.ulb.code.wit.resources.ServicePaths;
import be.ac.ulb.code.wit.resources.serializers.helpers.GroupSerializer;
import be.ac.ulb.code.wit.resources.serializers.helpers.NotFoundException;

/**
 * An atom serializer that generates atom entries representing contact groups.
 * 
 * @author fpicalausa
 * 
 */
public class AtomGroupSerializer extends GroupSerializer {
	private final Factory factory = Abdera.getInstance().getFactory();

	public AtomGroupSerializer(Contacts contacts) {
		super(contacts);
	}

	/**
	 * Creates an atom entry that represents a given group.
	 * 
	 * @param group
	 *            The group to be represented as an atom entry.
	 * @return an atom entry that represents a given group.
	 */
	private Entry makeGroupEntry(final String group) {
		if (!checkGroup(group)) {
			throw new NotFoundException();
		}

		final Entry entry = factory.newEntry();
		final String groupPath = ServicePaths.getURI(ServicePaths.GROUP,
				"group", group);

		entry.setTitle(group);
		entry.setEdited(contacts.getLastModified());

		entry.setId(groupPath);
		entry.addLink(groupPath, AtomHelpers.Relations.EDIT);
		entry.addLink(groupPath, AtomHelpers.Relations.SELF);
		entry.setContent(
				new IRI(ServicePaths.getURI(ServicePaths.GROUP_CONTACTS,
						"group", group)), Constants.FEED_MEDIA_TYPE);

		return entry;
	}

	/**
	 * Creates an atom feed that lists the contacts of a given group.
	 * 
	 * @return an atom feed that lists the contacts of a given group.
	 */
	@Override
	public String makeFeed() {
		final Feed groupsFeed = Abdera.getInstance().getFactory().newFeed();
		final Contacts contacts = this.contacts;

		groupsFeed.setId(ServicePaths.getURI(ServicePaths.GROUPS));
		groupsFeed.setTitle("Contact Groups");
		groupsFeed.setUpdated(contacts.getLastModified());
		groupsFeed.addLink(ServicePaths.getURI(ServicePaths.GROUPS), "self");

		for (String group : contacts.getGroups()) {
			groupsFeed.addEntry(makeGroupEntry(group));
		}

		return AtomHelpers.stringify(groupsFeed);
	}

	/**
	 * Creates an atom:entry String that represents a given group.
	 * 
	 * @param group
	 *            The group to be represented as an atom entry.
	 * @return an atom:entry String that represents a given group.
	 */
	@Override
	public String makeEntry(String group) {
		return AtomHelpers.stringify(makeGroupEntry(group));
	}
}
