package com.k_int.ciim.ui.resources;

import java.io.File;

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.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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.k_int.ciim.data.hdo.CIIMAttachmentHDO;
import com.k_int.ciim.ui.exceptions.NotAuthorisedException;
import com.k_int.ciim.ui.json.AttachmentJSON;
import com.k_int.ciim.ui.kernel.AttachmentQueryCore;
import com.k_int.ciim.ui.kernel.AttachmentTransactionCore;
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/attachments/{id}")
public class AttachmentResource extends AbstractResource
{
	@XmlTransient
	private static Log log = LogFactory.getLog(AttachmentResource.class);
	@XmlTransient
	private AttachmentQueryCore aqc;
	@XmlTransient
	private AttachmentTransactionCore atc;

	/* App Context setters */
	public void setAttachmentQueryCore(AttachmentQueryCore aqc) { this.aqc = aqc;	}
	public void setAttachmentTransactionCore(AttachmentTransactionCore atc) {	this.atc = atc;	}
	 
	public AttachmentResource(){;}
	
	@GET
	@Produces({MediaType.TEXT_HTML,MediaType.APPLICATION_XHTML_XML})
	public Viewable getHtml(@PathParam("id") Long id) 
	{
		return new Viewable("index",this);
	}
	
	@GET
	@Produces("application/json")
	public AttachmentJSON getJson(@PathParam("id") Long id) 
	{	
		AttachmentJSON retval = null;
		
		CIIMAttachmentHDO hdo = aqc.get(id);
		
		if(hdo != null)
		{
			retval = new AttachmentJSON(hdo);
		}
		
		return retval;
	}
	
	@POST
	@Produces({MediaType.TEXT_PLAIN})
	public String actions(	@PathParam("id") Long id,
							@QueryParam("action") String action)
	{	
		String retval = null;
		
		if(action.equalsIgnoreCase("delete"))
		{
			retval = this.delete(id);
		}
		
		return retval;
	}
	
	@DELETE
	@Produces({MediaType.TEXT_PLAIN})
	public String delete(@PathParam("id") Long id)
	{
		String retval = "Failed to delete attachment.";
		
		if(this.meetsRoleRequirement(RoleDefinitionEnum.CONFIGURED.toString()))
		{
			//get the path details
			CIIMAttachmentHDO hdo = aqc.get(id);
			
			if(hdo != null)
			{
				if(aqc.isAttachmentInUse(id))
				{
					throw new WebApplicationException(Response.status(Status.CONFLICT).entity("This attachment cannot be deleted as it has been used to create a Media record.").type("text/plain").build());
				}
				else
				{
					//create file from details
					File attachment = new File(hdo.getLocation() + File.separatorChar + hdo.getName());
		
					if(atc.delete(id))
					{
						//delete success so remove the file too
						attachment.delete();
						retval = "Attachment successfully deleted.";		
					}
				}
			}
		}
		else
		{
			throw new NotAuthorisedException();
		}  
	
		return retval;
	}	
	
	@POST
	@Path("/lookup")
	@Produces("application/json")
	public AttachmentJSON lookup(@PathParam("id") Long id,
						@QueryParam("filename") String filename)
	{	
		AttachmentJSON retval = null;

		log.error("filename to lookup:" + filename);
		
		CIIMAttachmentHDO hdo = aqc.get(filename);
			
		if(hdo != null)
		{
			retval = new AttachmentJSON(hdo);
		}
		else
		{
			throw new WebApplicationException(Response.status(Status.NOT_FOUND).entity("Attachment with the name " + filename + " could not be located.").type("text/plain").build());
		}
		
		return retval;
	}
}
