package com.k_int.ciim.ui.resources;

import javax.ws.rs.DELETE;
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.data.hdo.PropertyHDO;
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.PropertyJSON;
import com.k_int.ciim.ui.kernel.PropertyQueryCore;
import com.k_int.ciim.ui.kernel.PropertyTransactionCore;
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/properties/{id}")
public class PropertyResource extends AbstractResource
{
	private PropertyJSON resource = null;
	
	@XmlTransient
	private PropertyQueryCore pqc = null;
	@XmlTransient
	private PropertyTransactionCore ptc = null;
	
	/* App Context setters */
	public void setPropertyQueryCore(PropertyQueryCore pqc) {	this.pqc = pqc;	}
	public void setPropertyTransactionCore(PropertyTransactionCore ptc) {	this.ptc = ptc;	}
	
	public PropertyResource(){;}
	
	@GET
	@Produces({MediaType.TEXT_HTML,MediaType.APPLICATION_XHTML_XML})
	public Viewable getHtml(@PathParam("id") Long id) 
	{
		resource = new PropertyJSON(pqc.get(id));
		
		return new Viewable("index",this);
	}
	
	@GET
	@Produces("application/json")
	public PropertyJSON getJson(@PathParam("id") Long id) 
	{		
		return new PropertyJSON(pqc.get(id));
	}
	
	@POST
	@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;
	}
	
	@DELETE
	@Produces({MediaType.TEXT_PLAIN})
	public String delete(@PathParam("id") Long id)
	{
		String retval = "Failed to delete Property.";
		
		if(this.meetsRoleRequirement(RoleDefinitionEnum.SUPER.toString()))
		{
			try
			{
				if(ptc.delete(id))
				{
					retval = "Property successfully deleted.";		
				}
			}
			catch(MissingResourceException mre)//couldn't find schema section
			{
				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;
	}
	
	public String update(Long id, MultivaluedMap<String, String> form_params)
	{
		String retval = "Failed to update property";
		
		//user must be an editor to create a new property
		if(this.meetsRoleRequirement(RoleDefinitionEnum.SUPER.toString()))
		{
			//if null then no validation errors...
			if(validate(form_params) == null)
			{
				try
				{
					//...so create property
					PropertyHDO hdo = ptc.update(id, form_params);
					
					//if not null then the new property has been successfully created
					if(hdo != null)
					{
						retval = "Successfully updated property " + hdo.getName() + ".";
					}
				}
				catch(MissingResourceException mre)
				{
					throw new WebApplicationException(Response.status(Status.CONFLICT).entity(mre.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.";
		}
		
		return retval;
	}

	public PropertyJSON getResource() 
	{
		return resource;
	}

	public void setResource(PropertyJSON resource) 
	{
		this.resource = resource;
	}
}
