package com.novell.nam.custom.policy.action;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.omg.CORBA.RepositoryIdHelper;

import com.novell.nxpe.NxpeAction;
import com.novell.nxpe.NxpeContextDataElement;
import com.novell.nxpe.NxpeException;
import com.novell.nxpe.NxpeGroupedParameter;
import com.novell.nxpe.NxpeInformationContext;
import com.novell.nxpe.NxpeParameter;
import com.novell.nxpe.NxpeParameterList;
import com.novell.nxpe.NxpeResponseContext;
import com.novell.nxpe.NxpeResult;
import com.novell.nxpe.PolicyExtensionResponseParameters;
import com.novell.nxpe.PolicyExtensionResponseParameters.ActionExtResult;
import com.novell.nxpe.PolicyExtensionResponseParameters.PostDenyAction;

/**
 * This is an example code for a "Action" type of Policy Extension. doAction()
 * is the method which has to be modified by the user to code the action logic.
 * Most of other code can be retained as it is.
 */

public class PolicyActionExtDenyTemplate implements NxpeAction {

	/**
	 * ----BEGIN---- Initializing the constants for parameters passed to this
	 * class Configuration parameter can be configured from the administrator
	 * console UI. Go to Policies Tab->Extensions-><class extension>
	 * ->Configuration Parameters:->New
	 */

	/**
	 * Name parameter is used for reference in the code, can be used for
	 * logging. EV(Enumeration Value) will be used for fetching the parameter.
	 * This number must match the number configured at UI as ID parameter
	 */

	/**
	 * Unique string value for the condition. This value is used for tracing
	 * evaluation by policy engine
	 */
	private String interfaceID;

	/** Variable used to turn on/off the logging for debugging */
	private boolean debug;

	/** NxpeParameterList will be initialized during initialize() call */
	private NxpeParameterList configurationValues;

	/**
	 * This parameter is a string constant set in policy by the admin to turn
	 * debug on/off
	 */
	private static final String DEBUG_NAME = "Debug";
	private static final int EV_DEBUG = 91;

	/** This parameter is Credential Profile:LDAP Credentials:LDAP User DN */
	private static final String LDAP_USER_DN_NAME = "LDAP User DN";
	private static final int EV_LDAP_USER_DN = 41;

	/**
	 * Initialize the configuration values
	 * 
	 * @required
	 * @param configurationValues
	 *            :NxpeParameterList: The configuration parameters passed by
	 *            policy engine are used to initialize the NxpeCondition object
	 *            and are the parameters that the extension needs for evaluating
	 *            the action.
	 * 
	 * @throws com.novell.nxpe.NxpeException
	 */
	@Override
	public void initialize(NxpeParameterList configurationValues)
			throws NxpeException {
		this.configurationValues = configurationValues;
		/** set debug as true by Default */
		this.debug = true;
		setDebug(configurationValues);

	}

	/**
	 * Sets the unique string value for the condition. This value is used for
	 * tracing evaluation
	 */
	@Override
	public void setInterfaceId(String arg0) throws NxpeException {
		this.interfaceID = arg0;

	}

	/**
	 * Required: doAction() is the method which has to be modified by user to
	 * code the action evaluation logic required.This method is called by the
	 * policy engine when the action extension needs to be evaluated for a
	 * policy.
	 * 
	 * @param informationContext
	 *            :The informationContext parameter contains the parameter
	 *            information the extension needs from the policy engine to
	 *            evaluate the action.
	 * @param responseContext
	 *            :The responseCtx is a reflection object for communicating
	 *            detailed response information back to the application. This is
	 *            additional information and does not replace the need to place
	 *            an action result in the return value from this call.
	 * 
	 * @return NxpeResult: returns result whether the action is permit, deny,
	 *         obligation, error etc
	 * 
	 * @throws com.novell.nxpe.NxpeException
	 */
	@Override
	public NxpeResult doAction(NxpeInformationContext informationContext,
			NxpeResponseContext responseContext) throws NxpeException {

		 NxpeResult res = NxpeResult.GeneralFailure;
		 if (debug)
				System.out.println("PolicyActionExtnDenyTemplate : executing doAction() of PolicyActionExtnDenyTemplate policy");
		 		PolicyExtensionResponseParameters para = new PolicyExtensionResponseParameters();
		 
		 
		 try {
				/**
				 * 
				 * USER NEEDS TO PUT THE DENY ACTION EXTENSION EVALUATION LOGIC HERE
				 * 
				 */

				/**
				 * sample logic : begins This is a simple sample logic that returns
				 * "Success" & the browser displays the custom Deny message if LDAP UserDN is not empty or null otherwise it returns "GeneralFailure" and redirects the page to the given URL
				 */
	     
			 	para.setActionExtensionResultAction(ActionExtResult.DENY);
			 	String strLDAPUserDN = "";
			 	strLDAPUserDN = getLDAPUserDN(informationContext);
			 	
			 	if (strLDAPUserDN != null && !strLDAPUserDN.isEmpty()) {
			 		if (debug)
			 			System.out.println("PolicyActionExtDenyTemplate :strLDAPUserDN"
			 					+ strLDAPUserDN);
			
			 		res = NxpeResult.Success;
			 		
			 		//set custom deny message 
			 		para.setActionExtensionPostDenyAction(PostDenyAction.DENY_MESSAGE);
			 		para.setActionExtensionDenyMessage("You are not allowed!!");
			 
			 
			 
			 	}
			 	else
			 	{
			 		res = NxpeResult.ErrorDataUnavailable;
			 
			 		//set custom deny URL
			 		para.setActionExtensionPostDenyAction(PostDenyAction.REDIRECT_URL);
			 		para.setActionExtensionDenyRedirectURL("https://www.google.com");
			 	}
		 
		 responseContext.setExtensionResponseParameters(para);
		 /**
			 * sample logic: ends
		 **/
		 }
		 catch (NxpeException ex) {
				if (debug) {
					ex.printStackTrace();
				}
				res = NxpeResult.GeneralFailure; 
				/* When an exception is caught the default message will be displayed on the browser ("Access is
				*denied to this resource")
				*/
			}
	  	

		if (debug)
			System.out.println(" PolicyActionExtDenyTemplate : Exiting...");

		return res;
	}

	/**
	 * Enable/Disable the Debug logging Optional:
	 * 
	 * @param configurationValues
	 *            :NxpeParameterList
	 * 
	 * @throws com.novell.nxpe.NxpeException
	 */
	private void setDebug(NxpeParameterList configurationValues)
			throws NxpeException {

		/**
		 * Retrieve the value of "Debug"( value = 91) parameter set for this
		 * policy via admin console
		 */
		NxpeParameter parameter = configurationValues.getParameter(EV_DEBUG);

		if (parameter != null) {
			this.debug = Boolean.parseBoolean(parameter.getValue());
			System.out.println("PolicyActionExtDenyTemplate : " + DEBUG_NAME
					+ " : " + this.debug);
		}
	}

	/**
	 * This is a sample method to show how the values for configuration
	 * parameters can be retrieved at policy evaluation time from the
	 * NxpeInformationContext object that is passed by the policy engine. This
	 * method retrieves the LDAP UserDN as an example. Optional:
	 * 
	 * @param informationContext
	 *            : used to retrieve the values of configuration parameter
	 * @return String : value of the LDAP UserDN
	 * 
	 * @throws com.novell.nxpe.NxpeException
	 */
	private String getLDAPUserDN(NxpeInformationContext informationContext)
			throws NxpeException {
		NxpeParameter pLDAPUserDN;
		String strLDAPUserDN =null; 

		if ((pLDAPUserDN = this.configurationValues
				.getParameter(EV_LDAP_USER_DN)) != null) {
			/**
			 * Retrieve value of LDAP USER DN using informationContext NOTE: If
			 * your data is multi valued, then assign to an array
			 */
			strLDAPUserDN = (String) informationContext
					.getData(pLDAPUserDN);

			if (this.debug) {
				System.out.println("PolicyActionExtDenyTemplate : "
						+ LDAP_USER_DN_NAME + " : " + strLDAPUserDN);
			}

			
		} else {
			
			/**
			 * LDAP UserDN configuration parameter is not set for the policy.
			 * So, couldn't retrieve it's value
			 */
			NxpeException nxpeException = new NxpeException(
					NxpeResult.ErrorDataUnavailable,
					"PolicyActionExtTemplate :" + LDAP_USER_DN_NAME
							+ ": not present.");

			if (debug) {
				nxpeException.printStackTrace();
			}

			throw (nxpeException);
		}
		return strLDAPUserDN;
	}

}
