package com.k_int.ciim.ui.resources;

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.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.ref.PropertyTypeEnum;
import com.k_int.ciim.ui.exceptions.MissingResourceException;
import com.k_int.ciim.ui.exceptions.NotAuthorisedException;
import com.k_int.ciim.ui.exceptions.ResourceDeletionException;
import com.k_int.ciim.ui.json.SchemaJSON;
import com.k_int.ciim.ui.kernel.SchemaQueryCore;
import com.k_int.ciim.ui.kernel.SchemaTransactionCore;
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/schemas/{id}")
public class SchemaResource extends AbstractResource
{
	private SchemaJSON resource = null;
	
	@XmlTransient
	private SchemaQueryCore sqc = null;
	@XmlTransient
	private SchemaTransactionCore stc = null;
	
	private PropertyTypeEnum[] property_types = PropertyTypeEnum.values();
	
	/* App Context setters */
	public void setSchemaQueryCore(SchemaQueryCore sqc) {	this.sqc = sqc;	}
	public void setSchemaTransactionCore(SchemaTransactionCore stc) {	this.stc = stc;	}
	
	public SchemaResource(){;}
	
	@GET
	@Produces({MediaType.TEXT_HTML,MediaType.APPLICATION_XHTML_XML})
	public Viewable getHtml(@PathParam("id") Long id) 
	{
		resource = new SchemaJSON(sqc.get(id));
		
		return new Viewable("index",this);
	}
	
	@GET
	@Produces("application/json")
	public SchemaJSON getJson(@PathParam("id") Long id) 
	{		
		return new SchemaJSON(sqc.get(id));
	}
	
	@POST 
	@Consumes("application/x-www-form-urlencoded")
	@Produces({MediaType.TEXT_PLAIN})
	public String actions(	@PathParam("id") Long id,
							@QueryParam("action") String action,
							MultivaluedMap<String, String> form_params)
	{				
		String retval = null;
		
		if(action.equalsIgnoreCase("delete"))
		{
			retval = this.delete(id);
		}
		if(action.equalsIgnoreCase("update"))
		{
			retval = this.update(id, form_params);
		}
		
		return retval;
	}
	
	private String delete(Long id)
	{
		String retval = "Failed to delete Schema.";
		
		if(this.meetsRoleRequirement(RoleDefinitionEnum.SUPER.toString()))
		{
			try
			{
				if(stc.delete(id))
				{
					retval = "Schema successfully deleted.";		
				}
			}
			catch(MissingResourceException mre)
			{
				throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(mre.getMessage()).type("text/plain").build());
			}
			catch(ResourceDeletionException rde)
			{
				throw new WebApplicationException(Response.status(Status.CONFLICT).entity(rde.getMessage()).type("text/plain").build());
			}
		}
		else
		{
			throw new NotAuthorisedException();
		}  
	
		return retval;
	}
	
	private String update(Long id, MultivaluedMap<String, String> form_params)
	{
		String retval = "Failed to update Schema.";
		
		if(this.meetsRoleRequirement(RoleDefinitionEnum.SUPER.toString()))
		{
			//if null we have no validation errors
			if(validate(form_params) == null)
			{
				try
				{
					if(stc.update(id, form_params))
					{
						retval = "Schema successfully updated.";		
					}
				}
				catch(MissingResourceException mre)
				{
					throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(mre.getMessage()).type("text/plain").build());
				}
			}
			else
			{
				//return validation error message
				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.";
		}
		
		return retval;
	}
	
	public SchemaJSON getResource() 
	{
		return resource;
	}

	public void setResource(SchemaJSON resource) 
	{
		this.resource = resource;
	}
	
	public PropertyTypeEnum[] getPropertyTypes() 
	{
		return property_types;
	}
}
