package com.k_int.ciim.ui.user;

import javax.servlet.http.HttpServletRequest;
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.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
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.ResourceCreationException;
import com.k_int.ciim.ui.kernel.IdentServiceTransactionCore;
import com.sun.jersey.api.view.ImplicitProduces;
import com.sun.jersey.api.view.Viewable;

@XmlRootElement
@ImplicitProduces("text/html;qs=5")
@XmlAccessorType(XmlAccessType.FIELD)
@Path("/user/account")
public class AccountDetails
{
	@XmlTransient
	private IdentServiceTransactionCore istc = null;
	
	/* App context setters */
	public void setIdentServiceTransactionCore(IdentServiceTransactionCore istc){ this.istc = istc; }
	
	public AccountDetails(){;}
	
	@GET
	@Produces({MediaType.TEXT_HTML,MediaType.APPLICATION_XHTML_XML})
	public Viewable getHtml() 
	{
		return new Viewable("index",this);
	}
	
	@POST 
	@Consumes("application/x-www-form-urlencoded")
	@Produces({MediaType.TEXT_PLAIN})
	public String action(	@Context HttpServletRequest context,
							@QueryParam("action") String action, 
							MultivaluedMap<String, String> form_params)
	{
		String retval = null;
		
		if(action.equalsIgnoreCase("changePassword"))
		{
			String username = context.getUserPrincipal().getName();
			retval = changePassword(username, form_params);
		}
		
		return retval;
	}
	
	private String changePassword(String username, MultivaluedMap<String, String> form_params)
	{
		String retval= "Failed to change password.";
		
		try
		{
			if(istc.changePassword(username, form_params))
			{
				retval = "Successfully changed password.";
			}
		}
		catch(ResourceCreationException rce)
		{
			throw new WebApplicationException(Response.status(Status.CONFLICT).entity(rce.getMessage()).type("text/plain").build());
		}
		
		return retval;
	}
	
}
