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

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;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * An atom serializer that generates atom entries representing contact groups.
 * 
 * @author fpicalausa
 * 
 */
public class JsonGroupSerializer extends GroupSerializer {
	private final JsonNodeFactory factory = JsonNodeFactory.instance;

	public JsonGroupSerializer(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 JsonNode makeGroupEntry(final String group) {
		if (!checkGroup(group)) {
			throw new NotFoundException();
		}

		final ObjectNode n = factory.objectNode();

		n.put("group", group);
		n.put("href", ServicePaths.getURI(ServicePaths.GROUP_CONTACTS, true,
				"group", group));

		return n;
	}

	/**
	 * 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 ObjectNode root = factory.objectNode();
		final ArrayNode array = factory.arrayNode();
		final Contacts contacts = this.contacts;

		for (String group : contacts.getGroups()) {
			array.add(makeGroupEntry(group));
		}

		root.put("groups", array);

		return JsonHelpers.treeToString(root);
	}

	/**
	 * 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 JsonHelpers.treeToString(makeGroupEntry(group));
	}
}
