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

import java.io.Reader;
import java.util.Collection;

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.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.GROUP)
public class Group {
	private final Contacts contacts = ServiceConfiguration.getContacts();

	private GroupSerializer getGroupSerializer(MediaType mediaType) {
		return SerializationFactory.createGroupSerializer(mediaType, contacts);
	}

	private GroupDeserializer getGroupDeserializer(MediaType mediaType,
			String group) {
		return SerializationFactory.createGroupDeserializer(mediaType,
				contacts, group);
	}

	@GET
	@Produces({ MediaType.APPLICATION_JSON, Constants.ENTRY_MEDIA_TYPE })
	public Response getGroupJson(@Context HttpContext context,
			@PathParam("group") final String group) {
		MediaType mediaType = Util.getMediaOut(context);
		GroupSerializer serializer = getGroupSerializer(mediaType);
		return Response.ok(serializer.makeEntry(group)).build();
	}

	@PUT
	@Produces({ MediaType.APPLICATION_JSON, Constants.ENTRY_MEDIA_TYPE })
	@Consumes({ MediaType.APPLICATION_JSON, Constants.ENTRY_MEDIA_TYPE })
	public Response updateGroup(@Context HttpContext context,
			@PathParam("group") final String group, final Reader data) {
		MediaType mediaTypeIn = Util.getMediaIn(context);
		MediaType mediaTypeOut = Util.getMediaOut(context);
		GroupDeserializer deserializer = getGroupDeserializer(mediaTypeIn,
				group);
		GroupSerializer serializer = getGroupSerializer(mediaTypeOut);

		deserializer.updateGroup(data);

		return Response.ok(serializer.makeEntry(deserializer.getGroup()))
				.build();
	}

	@DELETE
	public Response destroyGroup(@PathParam("group") final String group) {
		Collection<IdentifiedContact> groupContacts = contacts
				.getContacts(group);
		for (IdentifiedContact c : groupContacts) {
			contacts.removeFromGroup(c, group);
		}
		return Response.ok().build();
	}
}
