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.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.resources.serializers.helpers.GroupDeserializer;
import be.ac.ulb.code.wit.resources.serializers.helpers.GroupSerializer;
import be.ac.ulb.code.wit.resources.serializers.helpers.SerializationFactory;

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

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

	@GET
	@Produces({ Constants.FEED_MEDIA_TYPE, MediaType.APPLICATION_JSON })
	public Response getGroups(@Context HttpContext context) {
		MediaType mediaType = Util.getMediaOut(context);
		GroupSerializer serializer = SerializationFactory
				.createGroupSerializer(mediaType, contacts);
		return Response.ok(serializer.makeFeed()).build();
	}

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

		GroupDeserializer deserializer = SerializationFactory
				.createGroupDeserializer(mediaTypeIn, contacts);
		GroupSerializer serializer = SerializationFactory
				.createGroupSerializer(mediaTypeOut, contacts);
		deserializer.updateGroup(data);
		return Response.created(serializer.getURI(deserializer.getGroup()))
				.entity(serializer.makeEntry(deserializer.getGroup())).build();
	}
}
