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

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.apache.abdera.Abdera;
import org.apache.abdera.model.Collection;
import org.apache.abdera.model.Service;
import org.apache.abdera.model.Workspace;
import org.apache.abdera.util.Constants;

import be.ac.ulb.code.wit.resources.serializers.AtomHelpers;

@Path(ServicePaths.SERVICEDOC)
public class ServiceDocument {
	private static final Service SERVICE_DOCUMENT = 
		Abdera.getInstance().getFactory().newService(); 
	
	/**
	 * Add a new collection to the given workspace.
	 * @param workspace The workspace that will receive the new collection
	 * @param title The atom title of the collection
	 * @param path The local path at which the collection is reachable
	 * @return The new collection.
	 */
	private Collection addCollection(final Workspace workspace, final String title, final String path) {
		final Collection collection = workspace.addCollection(title, path);
		collection.accepts(Constants.ENTRY_MEDIA_TYPE);
		return collection;
	}
	
	/**
	 * Retrieves the service document describing the contacts list service.
	 * @return
	 */
	public Service buildServiceDocument() {
		//If not created yet, create it
		if (SERVICE_DOCUMENT.getWorkspaces().isEmpty()) {
			SERVICE_DOCUMENT.setBaseUri(ServicePaths.BASE_URI);
			
			final Workspace workspace = SERVICE_DOCUMENT.addWorkspace("Contacts List");
			addCollection(workspace, "Contacts", "/contacts");
			addCollection(workspace, "Groups", "/groups");
		}
		return SERVICE_DOCUMENT;
	}
	
	/**
	 * Returns the service description document, formatted per RFC 5023.
	 * @return A positive response that includes the AtomPub Service Document.
	 */
     @GET 
     @Produces(Constants.APP_MEDIA_TYPE)
    public Response getServiceDocument() {
        return Response
        	.ok()
        	.entity(AtomHelpers.stringify(buildServiceDocument()))
        	.build();
    }
}
