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.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.SchemaHDO;
import com.k_int.ciim.ui.exceptions.NotAuthorisedException;
import com.k_int.ciim.ui.exceptions.ResourceCreationException;
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")
public class SchemaResources extends AbstractResource
{
	@XmlTransient
	private SchemaQueryCore sqc = null;
	@XmlTransient
	private SchemaTransactionCore stc = null;
	
	private List<SchemaJSON> schemas = new ArrayList<SchemaJSON>();
	
	/* App Context setters */
	public void setSchemaQueryCore(SchemaQueryCore sqc) {	this.sqc = sqc;	}
	public void setSchemaTransactionCore(SchemaTransactionCore stc) {	this.stc = stc;	}
	
	public SchemaResources(){;}
	
	@GET
	@Produces({MediaType.TEXT_HTML,MediaType.APPLICATION_XHTML_XML})
	public Viewable getHtml() 
	{
		schemas = this.convertToJSON(sqc.getAll());
		return new Viewable("index",this);
	}
	
	@GET
	@Produces("application/json")
	public List<SchemaJSON> getJson() 
	{		
		return this.convertToJSON(sqc.getAll());
	}
	
	@POST 
	@Consumes("application/x-www-form-urlencoded")
	@Produces({MediaType.TEXT_PLAIN})
	public String create(MultivaluedMap<String, String> form_params)
	{
		String retval = "Failed to create Schema.";
		
		//user must be an editor to create a new schema
		if(this.meetsRoleRequirement(RoleDefinitionEnum.SUPER.toString()))
		{
			//if null we have no validation errors
			if(validate(form_params) == null)
			{
				try
				{
					//...so create schema
					SchemaHDO hdo = stc.create(form_params);
					
					//if not null then the new schema has been successfully created
					if(hdo != null)
					{
						//return the id so that it can be used to load
						retval = hdo.getId().toString();
					}
				}
				catch(ResourceCreationException rce)
				{
					throw new WebApplicationException(Response.status(Status.CONFLICT).entity(rce.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;
	}
	
	/*
	 * Converts a list of SchemaHDO objects to a list of SchemaJSON objects
	 */
	private List<SchemaJSON> convertToJSON(List<SchemaHDO> schemas)
	{
		List<SchemaJSON> retval = new ArrayList<SchemaJSON>();
		
		if(schemas != null && schemas.size() > 0)
		{
			// Iterate through hdo's ...
			for(SchemaHDO hdo : schemas)
			{
				// ...and convert them to JSON
				retval.add(new SchemaJSON(hdo));
			}
		}
		
		return retval;
	}

	public List<SchemaJSON> getSchemas() {
		return schemas;
	}

	public void setSchemas(List<SchemaJSON> schemas) {
		this.schemas = schemas;
	}
}
