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.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.ContactDeserializer;
import be.ac.ulb.code.wit.resources.serializers.ContactSerializer;

@Path(ServicePaths.GROUP_CONTACT)
public class GroupContact {
	private static Contacts contacts = ServiceConfiguration.getContacts();

	@GET
	@Produces(Constants.ENTRY_MEDIA_TYPE)
	public Response getContact (
			@PathParam("contactid") final String contactId,
			@PathParam("group") final String group
			) {
		ContactSerializer serializer = new ContactSerializer(contacts, group);
		IdentifiedContact contact = serializer.getContact(contactId);
		final String entry = serializer.makeStringEntry(contact);
		return Response.ok(entry).build();
	}
	
	@PUT
    @Produces(Constants.ENTRY_MEDIA_TYPE)
    @Consumes(Constants.ENTRY_MEDIA_TYPE)
    public Response updateContact(
    		@PathParam("contactid") final String contactId, 
    		@PathParam("group") final String group,
    		final Reader data) {
        ContactSerializer serializer = new ContactSerializer(contacts, group);
		IdentifiedContact contact = serializer.getContact(contactId);
		
        ContactDeserializer deserializer = new ContactDeserializer(contacts, contact, null);
        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) {
		
		ContactDeserializer deserializer = 
				new ContactDeserializer(
						contacts, 
					    ContactSerializer.getContact(contactId, contacts),
						group);
		deserializer.removeContact();
		return Response.ok().build();
	}
}
