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

import java.io.Reader;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
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_CONTACT)
public class GroupContact {
	private static Contacts contacts = ServiceConfiguration.getContacts();

	@GET
	@Produces({ Constants.ENTRY_MEDIA_TYPE, MediaType.APPLICATION_JSON })
	public Response getContact(@Context HttpContext context,
			@PathParam("contactid") final String contactId,
			@PathParam("group") final String group) {
		MediaType mediaType = Util.getMediaOut(context);

		ContactSerializer serializer = SerializationFactory.createSerializer(
				mediaType, contacts, group);

		IdentifiedContact contact = serializer.getContact(contactId);
		final String entry = serializer.makeStringEntry(contact);
		return Response.ok(entry).build();
	}

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

		ContactSerializer serializer = SerializationFactory.createSerializer(
				mediaTypeOut, contacts, group);
		IdentifiedContact contact = serializer.getContact(contactId);

		ContactDeserializer deserializer = SerializationFactory
				.createDeserializer(mediaTypeIn, contacts, contact, group);
		deserializer.updateContact(data, false);

		return Response.ok(serializer.makeStringEntry(contact)).build();
	}

	@DELETE
	public Response deleteContact(
			@PathParam("contactid") final String contactId,
			@PathParam("group") final String group) {

		contacts.removeFromGroup(
				ContactSerializer.getContact(contactId, contacts), group);
		return Response.ok().build();
	}
}
