package com.k_int.ciim.ui.resources;

import javax.ws.rs.Consumes;
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.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.SchemaElementJSON;
import com.k_int.ciim.ui.kernel.SchemaElementQueryCore;
import com.k_int.ciim.ui.kernel.SchemaElementTransactionCore;
import com.k_int.ciim.ui.kernel.SchemaSectionTransactionCore;
import com.k_int.ciim.ui.ref.RoleDefinitionEnum;
import com.sun.jersey.api.view.ImplicitProduces;

@XmlRootElement
@ImplicitProduces("text/html;qs=5") //for FireFox?
@XmlAccessorType(XmlAccessType.FIELD)
@Path("/resources/schemas/{schema_id}/sections/{section_id}/elements/{id}")
public class SchemaElementResource extends AbstractResource
{
	private SchemaElementJSON resource = null;
	
	@XmlTransient
	private SchemaElementQueryCore seqc = null;
	@XmlTransient
	private SchemaSectionTransactionCore sstc = null;
	@XmlTransient
	private SchemaElementTransactionCore setc = null;
	
	/* App Context setters */
	public void setSchemaElementQueryCore(SchemaElementQueryCore seqc) {	this.seqc = seqc;	}
	public void setSchemaSectionTransactionCore(SchemaSectionTransactionCore sstc) {	this.sstc = sstc;	}
	public void setSchemaElementTransactionCore(SchemaElementTransactionCore setc) {	this.setc = setc;	}
	
	
	public SchemaElementResource(){;}
		
	@GET
	@Produces("application/json")
	public SchemaElementJSON getJson(@PathParam("schema_id") Long schema_id,
									 @PathParam("section_id") Long section_id,
									 @PathParam("id") Long id) 
	{		
		return new SchemaElementJSON(seqc.get(id));
	}
	
	private String move(Long schema_id,
						Long section_id,
						Long id,
						Long target_section,
						Integer target_position)
	{
		String retval = "failed to move element";
		
		//user must be an editor to create a new schema
		if(this.meetsRoleRequirement(RoleDefinitionEnum.SUPER.toString()))
		{
			try
			{
				sstc.moveElement(schema_id, section_id, id, target_section, target_position);
				retval = "successfully moved element";
			}
			catch(MissingResourceException mre)//couldn't find schema section
			{
				throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(mre.getMessage()).type("text/plain").build());
			}
		}
		else
		{
			throw new NotAuthorisedException();
		}  
		
		return retval;
	}
	
	@POST
	@Produces({MediaType.TEXT_PLAIN})
	public String actions(	@PathParam("schema_id") Long schema_id,
							@PathParam("section_id") Long section_id,
							@PathParam("id") Long id,
							@QueryParam("target_section") Long target_section,
							@QueryParam("target_position") Integer target_position,
							@QueryParam("action") String action)
	{				
		String retval = null;
		
		if(action.equalsIgnoreCase("delete"))
		{
			retval = this.delete(schema_id, section_id, id);
		}
		else if(action.equalsIgnoreCase("move"))
		{
			retval = this.move(schema_id, section_id, id, target_section, target_position);
		}
		
		return retval;
	}
	
	@POST
	@Consumes("application/x-www-form-urlencoded")
	@Produces({MediaType.TEXT_PLAIN})
	public String actions(	@PathParam("schema_id") Long schema_id,
							@PathParam("section_id") Long section_id,
							@PathParam("id") Long id,
							@QueryParam("action") String action,
							MultivaluedMap<String, String> form_params)
	{				
		String retval = null;
		
		if(action.equalsIgnoreCase("update"))
		{
			retval = this.update(id, form_params);
		}
		else if(action.equalsIgnoreCase("delete"))
		{
			retval = this.delete(schema_id, section_id, id);
		}
		
		return retval;
	}
	
	@DELETE
	@Produces({MediaType.TEXT_PLAIN})
	public String delete(	@PathParam("schema_id") Long schema_id,
							@PathParam("section_id") Long section_id,
							@PathParam("id") Long id)
	{
		String retval = "Failed to delete Schema Field.";
		
		if(this.meetsRoleRequirement(RoleDefinitionEnum.SUPER.toString()))
		{
			try
			{
				if(sstc.deleteElement(section_id, id))
				{
					retval = "Schema Field 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;
	}
	
	private String update(Long id, MultivaluedMap<String, String> form_params)
	{				
		String retval = "Failed to update Schema Field";
		
		if(this.meetsRoleRequirement(RoleDefinitionEnum.SUPER.toString()))
		{
			try
			{
				if(setc.update(id, form_params))
				{
					retval = "Successfully updated Schema Field.";
				}
			}
			catch(MissingResourceException mre)
			{
				throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(mre.getMessage()).type("text/plain").build());
			}
		}
		else
		{
			throw new NotAuthorisedException();
		}  
		
		return retval;
	}

	public SchemaElementJSON getResource() 
	{
		return resource;
	}

	public void setResource(SchemaElementJSON resource) 
	{
		this.resource = resource;
	}
}
