package com.k_int.ciim.ui.resources;

import java.util.ArrayList;
import java.util.List;

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.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import com.k_int.ciim.data.hdo.ContextHDO;
import com.k_int.ciim.ui.exceptions.NotAuthorisedException;
import com.k_int.ciim.ui.exceptions.ResourceCreationException;
import com.k_int.ciim.ui.json.ContextJSON;
import com.k_int.ciim.ui.kernel.ContextQueryCore;
import com.k_int.ciim.ui.kernel.ContextTransactionCore;
import com.k_int.ciim.ui.ref.RoleDefinitionEnum;
import com.sun.jersey.api.view.ImplicitProduces;
import com.sun.jersey.api.view.Viewable;

@XmlRootElement
@ImplicitProduces("text/html;qs=5") //for FireFox?
@XmlAccessorType(XmlAccessType.FIELD)
@Path("/resources/contexts")
public class ContextResources extends AbstractResource
{
	private List<ContextJSON> contexts = new ArrayList<ContextJSON>();
	
	@XmlTransient
	private ContextQueryCore cqc = null;
	@XmlTransient
	private ContextTransactionCore ctc = null;
	
	/* App Context setters */
	public void setContextQueryCore(ContextQueryCore cqc) {	this.cqc = cqc;	}
	public void setContextTransactionCore(ContextTransactionCore ctc) {	this.ctc = ctc;	}
	
	public ContextResources(){;}
	
	@GET
	@Produces({MediaType.TEXT_HTML,MediaType.APPLICATION_XHTML_XML})
	public Viewable getHtml() 
	{
		contexts = this.convertToJSON(cqc.getAll());
		return new Viewable("index",this);
	}
	
	@GET
	@Produces("application/json")
	public List<ContextJSON> getJson(@QueryParam("identifier") String identifier) 
	{
		if(identifier == null || identifier.trim().length() == 0)
		{
			return this.convertToJSON(cqc.getAllByUser(request.getUserPrincipal().getName()));
		}
		else
		{
			return this.convertToJSON(cqc.getAllUnlinked(identifier));
		}
	}
	
	
	@POST 
	@Consumes("application/x-www-form-urlencoded")
	@Produces({MediaType.TEXT_PLAIN})
	public String create(MultivaluedMap<String, String> form_params)
	{
		String retval = "Failed to create Context.";
		
		//user must be an editor to create a new context
		if(this.meetsRoleRequirement(RoleDefinitionEnum.SUPER.toString()))
		{
			//if null we have no validation errors
			if(validate(form_params) == null)
			{
				try
				{
					//...so create context
					ContextHDO hdo = ctc.create(form_params, request.getUserPrincipal().getName());
					
					//if not null then the new context has been successfully created
					if(hdo != null)
					{
						retval = hdo.getId().toString();
					}
				}
				catch(ResourceCreationException rce)
				{
					throw new WebApplicationException(Response.status(Status.CONFLICT).entity(rce.getMessage()).type("text/plain").build());
				}
			}
			else
			{
				throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(validate(form_params)).type("text/plain").build());
			}
		}
		else
		{
			throw new NotAuthorisedException();
		}
		
		return retval;
	}
	
	private String validate(MultivaluedMap<String, String> form_params)
	{
		String retval = null;
		
		if(form_params.getFirst("name") == null || form_params.getFirst("name").trim().length() == 0)
		{
			return "name is required.";
		}
		else if(form_params.getFirst("name").trim().equalsIgnoreCase("GLOBAL"))
		{
			return form_params.getFirst("name") + " is a reserved name, please try something else.";
		}
		else if(form_params.getFirst("description") == null || form_params.getFirst("description").trim().length() == 0)
		{
			return "description is required.";
		}
		else if(form_params.getFirst("purpose") == null || form_params.getFirst("purpose").trim().length() == 0 || form_params.getFirst("purpose").equalsIgnoreCase("Please Select"))
		{
			return "purpose is required.";
		}
		
		return retval;
	}
	
	/*
	 * Converts a list of ContextHDO objects to a list of ContextJSON objects
	 */
	private List<ContextJSON> convertToJSON(List<ContextHDO> contexts)
	{
		List<ContextJSON> retval = new ArrayList<ContextJSON>();
		
		if(contexts != null && contexts.size() > 0)
		{
			// Iterate through hdo's ...
			for(ContextHDO hdo : contexts)
			{
				// ...and convert them to JSON
				retval.add(new ContextJSON(hdo));
			}
		}
		
		return retval;
	}
	
	public List<ContextJSON> getContexts() 
	{
		return contexts;
	}

	public void setSchemas(List<ContextJSON> contexts) 
	{
		this.contexts = contexts;
	}
}
