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

import java.io.Reader;

import be.ac.ulb.code.wit.contacts.Contacts;
import be.ac.ulb.code.wit.resources.serializers.helpers.GroupDeserializer;
import be.ac.ulb.code.wit.resources.serializers.helpers.MalformedRequestException;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * An atom deserializer that creates, renames or deletes contact groups, using
 * data from atom entries.
 */
public class JsonGroupDeserializer extends GroupDeserializer {
	public JsonGroupDeserializer(Contacts contacts) {
		super(contacts);
	}

	public JsonGroupDeserializer(Contacts contacts, String group) {
		super(contacts, group);
	}

	/**
	 * Update the current group or create a new one, with the information
	 * contained in an atom entry that can be read from the given reader.
	 * 
	 * @param data
	 *            The reader from which the atom entry containing the new
	 *            information about the group is to be read.
	 * @throws MalformedRequestException
	 *             if the given entry is not correct.
	 */
	@Override
	public void updateGroup(final Reader data) throws MalformedRequestException {
		try {
			ObjectMapper mapper = new ObjectMapper();
			JsonNode tree = mapper.readValue(data, JsonNode.class);
			setGroup(tree.get("group").asText());
		} catch (Exception e) {
			throw new MalformedRequestException(e);
		}
	}
}
