package flow;

import java.io.IOException;
import java.util.Properties;

import com.avaya.sce.runtime.tracking.ReportInfo;
import com.avaya.sce.runtimecommon.IReportInfo;

import flow.constants.SSAConstants;
import flow.utils.Utils;

/**
 * A basic servlet which allows a user to define their code, generate
 * any output, and to select where to transition to next.
 * Last generated by Orchestration Designer at: (timestamp generation disabled)
 */
public class LoadProperties extends com.avaya.sce.runtime.BasicServlet {

	//{{START:CLASS:FIELDS
	//}}END:CLASS:FIELDS

	/**
	 * Default constructor
	 * Last generated by Orchestration Designer at: (timestamp generation disabled)
	 */
	public LoadProperties() {
		//{{START:CLASS:CONSTRUCTOR
		super();
		//}}END:CLASS:CONSTRUCTOR
	}

	/**
	 * This method allows for custom integration with other Java components.
	 * You may use Java for sophisticated logic or to integrate with custom
	 * connectors (i.e. JMS, custom web services, sockets, XML, JAXB, etc.)
	 *
	 * Any custom code added here should work as efficiently as possible to prevent delays.
	 * It's important to design your callflow so that the voice browser (Voice Portal/IR)
	 * is not waiting too long for a response as this can lead to a poor caller experience.
	 * Additionally, if the response to the client voice browser exceeds the configured
	 * timeout, the platform may throw an "error.badfetch". 
	 *
	 * Using this method, you have access to all session variables through the 
	 * SCESession object.
	 *
	 * The code generator will *** NOT *** overwrite this method in the future.
	 * Last generated by Orchestration Designer at: (timestamp generation disabled)
	 */
	public void servletImplementation(com.avaya.sce.runtimecommon.SCESession mySession) {

		//Read properties and store them in the OD variables
		Properties properties = null;
		try {
            String uuiInbound = Utils.getVariableField(IProjectVariables.SESSION, IProjectVariables.SESSION_FIELD_UUI, mySession);
            String dnis = Utils.getVariableField(IProjectVariables.SESSION, IProjectVariables.SESSION_FIELD_DNIS, mySession);
            
			//Work ID = UCID (Universal Call Identifier) can be retrieved from session variable
            Utils.logInfo("==>Incoming call received for " + new Start().getEntryName() + "; UCID Received: " + Utils.getVariableField(IProjectVariables.SESSION, IProjectVariables.SESSION_FIELD_UCID, mySession) +
            		"; UUI Received: " + uuiInbound, mySession);
            
            //Check for a transfer in to this app from an existing Oceana call
            String existingContextId = Utils.parseUserData(uuiInbound, mySession);            
            if (!Utils.isStringBlank(existingContextId)) {
            	
    			Utils.logInfo("Existing context detected (" + existingContextId + ")", mySession);
    			
    			//If an Oceana context id can be parsed out from the incoming call, then use this. No need to re-prompt for an a/c number or create new context
    			//Set this as the CS_ID
    			Utils.setVariableField(IProjectVariables.CONTEXT, IProjectVariables.CONTEXT_FIELD_CONTEXT_ID, existingContextId, mySession);    			    		 
            }
            			
			String callID = Utils.getContactID(mySession);
			Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_CALL_ID, callID, mySession);
			
	        ReportInfo report =  new com.avaya.sce.runtime.tracking.ReportInfo(
	                IReportInfo.REPORT_TYPE_START_TRANS, 
	                IReportInfo.ALARM_LEVEL_INFO, 
	                SSAConstants.REPORTING_TAG, "Shared Contact ID", callID);	        
	        report.trackItems(mySession); 
			
			properties = Utils.getPropertiesFile(this.getServletContext(), mySession);
			
			Utils.logInfo("Loaded properties file (" + SSAConstants.CONF_FILE_PROPERTIES + ") successfully.", mySession);	       
			
            String xferType = properties.getProperty("TransferType");
            String useCustomerAPI = properties.getProperty("CustomerAPI");
            String locale = properties.getProperty("Locale");
            String priority = properties.getProperty("Priority");
            String priorityCustomer = properties.getProperty("PriorityCustomer");			
            String rank = properties.getProperty("Rank");
            String strategy = properties.getProperty("Strategy");
            String resource = properties.getProperty("SpecifiedResource");
            String q2Multiple = properties.getProperty("Queue2Multiple");
            String waMetricsURL = properties.getProperty("WAMetricsURL");
            String ucmInitContactURL = properties.getProperty("UCMInitContactURL");
            String ucmCompleteContactURL = properties.getProperty("UCMCompleteContactURL");            
            String proficiencyMin = properties.getProperty("MinProficiency");
            String proficiencyMax = properties.getProperty("MaxProficiency");
            String topic = properties.getProperty("Topic");			
            String accountType = properties.getProperty("AccountType");
            String accountLength = properties.getProperty("AccountLength");
            String crmId = properties.getProperty("CRMIdentifier");
            String callerType = properties.getProperty("CallerType");
            String ucaResourceURL = properties.getProperty("UCAGetResourceListURL");
            
            // Hardwire menu selections for Traffic testing
            String trafficProfileADialledNumber = properties.getProperty("TrafficProfileADialledNumber");
            String trafficProfileBDialledNumber = properties.getProperty("TrafficProfileBDialledNumber");
            String trafficFirstMenuSelection=properties.getProperty("FirstMenuSelection");
            String trafficSecondMenuSelection=properties.getProperty("SecondMenuSelection");
            String trafficUseCRM=properties.getProperty("UseCRM");            
            
            Utils.logInfo("Transfer Type: [" + xferType + "]", mySession);
            Utils.logInfo("Use Customer API: [" + useCustomerAPI + "]", mySession);
            Utils.logInfo("Locale: [" + locale + "]", mySession);
            Utils.logInfo("Priority: [" + priority + "]", mySession);
            Utils.logInfo("Queue To Multiple Services: [" + q2Multiple + "]", mySession);
            
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_XFER_TYPE, xferType, mySession);
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_USE_CUSTOMER_API, useCustomerAPI, mySession);
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_LOCALE, locale, mySession);
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_PRIORITY, priority, mySession);    			
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_PRIORITY_CUSTOMER, priorityCustomer, mySession);
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_STRATEGY, strategy, mySession);         
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_CONFIGURED_SPECIFIED_RESOURCE, resource, mySession);
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_WAMETRICS_URL, waMetricsURL, mySession);
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_UCMCREATE_CONTACT_URL, ucmInitContactURL, mySession);
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_UCMCOMPLETE_CONTACT_URL, ucmCompleteContactURL, mySession);
            Utils.setVariableField(IProjectVariables.Q_2MULTIPLE_SERVICES, q2Multiple, mySession);
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_RANK, rank, mySession);         
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_MIN_PROFICIENCY, proficiencyMin, mySession);         
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_MAX_PROFICIENCY, proficiencyMax, mySession);         
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_TOPIC, topic, mySession);	
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_ACCOUNT_TYPE, accountType, mySession);
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_ACCOUNT_LENGTH, accountLength, mySession);            
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_CRMIDENTIFIER, crmId, mySession); 
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_CALLER_TYPE, callerType, mySession);
            Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_UCAGET_RESOURCE_LIST_URL, ucaResourceURL, mySession);
        	
            //Read the phrases and store in variables
	        String welcomeText = properties.getProperty("Welcome");
			String askCustomerIDText = properties.getProperty("AskCustomerID");
			String invalidCustomerIDText = properties.getProperty("InvalidCustomerID");
			String askMenuText = properties.getProperty("AskMenu");
			String askSpecifiedResourceText = properties.getProperty("AskResource");
			String waitToBeTransferedText = properties.getProperty("WaitToBeTransfered");
			String unstaffedText = properties.getProperty("UnStaffed");			
            String announceErrorText = properties.getProperty("AnnounceError");
            String invalidCDNText = properties.getProperty("InvalidCDN");
            String invalidDNText = properties.getProperty("InvalidDN");
            String metricsFailedText = properties.getProperty("MetricsFailed");
            String contextFailedText = properties.getProperty("ContextFailed");            
            String contactFailedText = properties.getProperty("ContactFailed");
            String transferText = properties.getProperty("Transfer");           
            String errorTransferText = properties.getProperty("ErrorTransfer");
            String getCustomerFailedText = properties.getProperty("GetCustomerFailed");
	        
	        //RequestType
            String requestTypeText = properties.getProperty("RequestType");
            
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_WELCOME, welcomeText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_ASK_MENU_1, askMenuText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_ASK_MENU_2, askMenuText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_ASK_MENU_3, requestTypeText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_WAIT_TO_BE_TRANSFERRED, waitToBeTransferedText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_ASK_CUSTOMER_ID, askCustomerIDText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_INVALID_CUSTOMER_ID, invalidCustomerIDText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_UN_STAFFED, unstaffedText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_ANNOUNCE_ERROR, announceErrorText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_INVALID_CDN, invalidCDNText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_INVALID_DN, invalidDNText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_METRICS_FAILED, metricsFailedText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_CONTEXT_FAILED, contextFailedText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_CONTACT_FAILED, contactFailedText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_TRANSFER, transferText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_ERROR_TRANSFER, errorTransferText, mySession);
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_GET_CUST_FAILED, getCustomerFailedText, mySession);
			
			// Initialise empty error message
			Utils.setVariableField(IProjectVariables.PROMPTS, IProjectVariables.PROMPTS_FIELD_ERROR_MESSAGE, "", mySession);

			//Check if secure URLs are being used
			String isSecure = (String) Utils.getVariableField(IProjectVariables.AVAYA_OCEANA_USE_SECURE_CONNECTION, mySession);			
			if (!Utils.isStringBlank(isSecure) && isSecure.equalsIgnoreCase("true")) {		
				Utils.logInfo("Using secure URLs", mySession);
				
				String WAMetricsURL = (String)Utils.getVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_WAMETRICS_URL, mySession);				
				String UCMInitContactURL = (String)Utils.getVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_UCMCREATE_CONTACT_URL, mySession);
				String UCMCompleteContactURL = (String)Utils.getVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_UCMCOMPLETE_CONTACT_URL, mySession);
				String UCAResourceURL = (String)Utils.getVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_UCAGET_RESOURCE_LIST_URL, mySession);
			
				Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_WAMETRICS_URL, WAMetricsURL.replaceFirst(SSAConstants.HTTP_REGULAR, SSAConstants.HTTP_SECURE), mySession);					
				Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_UCMCREATE_CONTACT_URL, UCMInitContactURL.replaceFirst(SSAConstants.HTTP_REGULAR, SSAConstants.HTTP_SECURE), mySession);
				Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_UCMCOMPLETE_CONTACT_URL, UCMCompleteContactURL.replaceFirst(SSAConstants.HTTP_REGULAR, SSAConstants.HTTP_SECURE), mySession);
				Utils.setVariableField(IProjectVariables.PROPERTIES, IProjectVariables.PROPERTIES_FIELD_UCAGET_RESOURCE_LIST_URL, UCAResourceURL.replaceFirst(SSAConstants.HTTP_REGULAR, SSAConstants.HTTP_SECURE), mySession);
			}	
			
			//Check if one of the Traffic Profiles is being used			
			if (!Utils.isStringBlank(trafficProfileADialledNumber)) {			
				String profileANumbers[] = trafficProfileADialledNumber.split(SSAConstants.DELIMITER_COMMA + "\\s*");
				for(String profileANumber : profileANumbers){ 
					if(profileANumber.equalsIgnoreCase(dnis)){	
						//Variable defaulted to false; only set true if the dialled number matches one of the values defined in configuration 
						Utils.setVariableField(IProjectVariables.TRAFFIC_BYPASS, IProjectVariables.TRAFFIC_BYPASS_FIELD_TRAFFIC_PROFILE_AENABLED, "true", mySession);
						break;
	                }
				}
			}

			if (!Utils.isStringBlank(trafficProfileBDialledNumber)) {			
				String profileBNumbers[] = trafficProfileBDialledNumber.split(SSAConstants.DELIMITER_COMMA + "\\s*");
				for(String profileBNumber : profileBNumbers){ 
					if(profileBNumber.equalsIgnoreCase(dnis)){
						//Variable defaulted to false; only set true if the dialled number matches one of the values defined in configuration					
						Utils.setVariableField(IProjectVariables.TRAFFIC_BYPASS, IProjectVariables.TRAFFIC_BYPASS_FIELD_TRAFFIC_PROFILE_BENABLED, "true", mySession);
						break;						
	                }
				}
			}
			
            Utils.setVariableField(IProjectVariables.TRAFFIC_BYPASS, IProjectVariables.TRAFFIC_BYPASS_FIELD_FIRST_MENU_SELECTION, trafficFirstMenuSelection, mySession);
            Utils.setVariableField(IProjectVariables.TRAFFIC_BYPASS, IProjectVariables.TRAFFIC_BYPASS_FIELD_SECOND_MENU_SELECTION, trafficSecondMenuSelection, mySession);
            Utils.setVariableField(IProjectVariables.TRAFFIC_BYPASS, IProjectVariables.TRAFFIC_BYPASS_FIELD_USE_CRM, trafficUseCRM, mySession);            			
			
		} catch (IOException ioe) {
			ReportInfo exceptionReport = new ReportInfo( IReportInfo.REPORT_TYPE_PROGRESS, IReportInfo.ALARM_LEVEL_MAJOR, SSAConstants.REPORTING_TAG, "Error loading properties file (" + SSAConstants.CONF_FILE_PROPERTIES + ")", ioe.getMessage()); 
			exceptionReport.trackItems(mySession);
		}				
	}
	/**
	 * Builds the list of branches that are defined for this servlet object.
	 * This list is built automatically by defining Goto nodes in the call flow editor.
	 * It is the programmer's responsibilty to provide at least one enabled Goto.<BR>
	 *
	 * The user should override updateBranches() to determine which Goto that the
	 * framework will activate.  If there is not at least one enabled Goto item, 
	 * the framework will throw a runtime exception.<BR>
	 *
	 * This method is generated automatically and changes to it may
	 * be overwritten next time code is generated.  To modify the list
	 * of branches for the flow item, override:
	 *     <code>updateBranches(Collection branches, SCESession mySession)</code>
	 *
	 * @return a Collection of <code>com.avaya.sce.runtime.Goto</code>
	 * objects that will be evaluated at runtime.  If there are no gotos
	 * defined in the Servlet node, then this returns null.
	 * Last generated by Orchestration Designer at: (timestamp generation disabled)
	 */
	public java.util.Collection getBranches(com.avaya.sce.runtimecommon.SCESession mySession) {
		java.util.List list = null;
		com.avaya.sce.runtime.Goto aGoto = null;
		list = new java.util.ArrayList(1);

		aGoto = new com.avaya.sce.runtime.Goto("LoadConfigurationData", 0, true, "Default");
		list.add(aGoto);

		return list;
	}
}
