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

import java.io.Reader;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.abdera.util.Constants;

import be.ac.ulb.code.wit.ServiceConfiguration;
import be.ac.ulb.code.wit.contacts.Contacts;
import be.ac.ulb.code.wit.contacts.Contacts.IdentifiedContact;
import be.ac.ulb.code.wit.resources.serializers.helpers.ContactDeserializer;
import be.ac.ulb.code.wit.resources.serializers.helpers.ContactSerializer;
import be.ac.ulb.code.wit.resources.serializers.helpers.SerializationFactory;

import com.sun.jersey.api.core.HttpContext;

@Path(ServicePaths.GROUP_CONTACTS)
public class GroupContacts {
	private final Contacts contacts = ServiceConfiguration.getContacts();

	@GET
	@Produces({ Constants.FEED_MEDIA_TYPE, MediaType.APPLICATION_JSON })
	public Response getContacts(@Context HttpContext context,
			@PathParam("group") final String group) {
		MediaType mediaType = Util.getMediaOut(context);
		ContactSerializer serializer = SerializationFactory.createSerializer(
				mediaType, contacts, group);
		return Response.ok(serializer.makeFeed()).build();
	}

	@POST
	@Produces({ Constants.ENTRY_MEDIA_TYPE, MediaType.APPLICATION_JSON })
	@Consumes({ Constants.FEED_MEDIA_TYPE, MediaType.APPLICATION_JSON })
	public Response createGroupContacts(@Context HttpContext context,
			@PathParam("group") final String group, Reader data) {
		MediaType mediaTypeIn = Util.getMediaIn(context);
		MediaType mediaTypeOut = Util.getMediaOut(context);

		ContactSerializer serializer = SerializationFactory.createSerializer(
				mediaTypeOut, contacts, group);
		ContactDeserializer deserializer = SerializationFactory
				.createDeserializer(mediaTypeIn, contacts, group);

		// If the contact has a know id, add it to the group instead of creating
		// it
		deserializer.updateContact(data, group != Contacts.GROUP_ALLCONTACTS);

		IdentifiedContact contact = deserializer.getIdentifiedContact();

		return Response.created(serializer.getContactURL(contact))
				.entity(serializer.makeStringEntry(contact)).build();
	}
}
