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.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_CONTACTS)
public class GroupContacts {
	private final Contacts contacts = ServiceConfiguration.getContacts();
	
	@GET
    @Produces(Constants.FEED_MEDIA_TYPE)
    public Response getContacts(@PathParam("group") final String group) {
		ContactSerializer serializer = new ContactSerializer(contacts, group);
		return Response.ok(serializer.makeFeed()).build();
	}
	
	@POST
    @Consumes(Constants.ENTRY_MEDIA_TYPE)
    @Produces(Constants.ENTRY_MEDIA_TYPE)
    public Response createGroupContacts(@PathParam("group") final String group, Reader data) {
        ContactDeserializer deserializer = new ContactDeserializer(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); 
        
        ContactSerializer serializer = new ContactSerializer(contacts, group);	          
        IdentifiedContact contact = deserializer.getIdentifiedContact();
        
		return Response
            .created(serializer.getURL(contact))
			.entity(serializer.makeStringEntry(contact))
			.build();
	}
}
