package com.acme.intg.processes; 

import com.bea.control.ServiceBrokerControl;
import com.bea.wli.control.broker.MessageBroker;
import com.bea.wli.jpd.Callback;
import com.bea.wli.jpd.CallbackInterface;
import com.bea.xml.XmlObjectList;
import java.util.Random;

import com.bea.jpd.JpdContext;
import com.bea.data.RawData;
import org.apache.beehive.controls.api.bean.Control;
import org.apache.beehive.controls.api.events.EventHandler;
import org.apache.xmlbeans.XmlObject;

import com.acme.logging.AppLogger;
import java.text.SimpleDateFormat;

import com.acme.util.Parameters;


/**
 * @author Selvan V. Rajan
 * @version 1.0 
 * 
 * @jpd:process process::
 * <process name="CreditCard Validation &amp; Authorization Process">
 *   <clientRequest name="Client Request with Return" method="clientRequest" returnMethod="clientReturn">
 *     <perform name="Check Credit Card" method="checkCreditCard"/>
 *     <controlSend name="Validate and Check Credit Card" method="ccTxnInsertCheckBal"/>
 *     <decision name="Decision">
 *       <if name="isValidCard" conditionMethod="getValidationCode">
 *         <controlSend name="Update CC Master With New Bal" method="ccTxnInsertUpdateCCMaster"/>
 *       </if>
 *       <default name="Invalid CC Number">
 *         <perform name="Log Error Message" method="logInvalidMessageTypeError"/>
 *       </default>
 *     </decision>
 *     <controlSend name="Create Outbound XML" method="toOutboundXMLConvertInXMLToOutXML"/>
 *     <controlSend name="Call Db Control to Insert Txn" method="ccTxnInsertInsertTxn"/>
 *   </clientRequest>
 * </process>::
 */
@com.bea.wli.jpd.Process(process = "<process name=\"CreditCard Validation &amp; Authorization Process\"> " +
                                   "  <clientRequest name=\"Client Request with Return\" method=\"clientRequest\" returnMethod=\"clientReturn\"> " +
                                   "    <perform name=\"Check Credit Card\" method=\"checkCreditCard\"/> " +
                                   "    <controlSend name=\"Validate and Check Credit Card\" method=\"ccTxnInsertCheckBal\"/> " +
                                   "    <decision name=\"Decision\"> " +
                                   "      <if name=\"isValidCard\" conditionMethod=\"getValidationCode\"> " +
                                   "        <controlSend name=\"Update CC Master With New Bal\" method=\"ccTxnInsertUpdateCCMaster\"/> " +
                                   "      </if> " +
                                   "      <default name=\"Invalid CC Number\"> " +
                                   "        <perform name=\"Log Error Message\" method=\"logInvalidMessageTypeError\"/> " +
                                   "      </default> " +
                                   "    </decision> " +
                                   "    <controlSend name=\"Create Outbound XML\" method=\"toOutboundXMLConvertInXMLToOutXML\"/> " +
                                   "    <controlSend name=\"Call Db Control to Insert Txn\" method=\"ccTxnInsertInsertTxn\"/> " +
                                   "  </clientRequest> " +
                                   "</process>")
public class CreditCardValidationProcess implements com.bea.jpd.ProcessDefinition
{
    public float reqAmount;

    public float availBal;

    public long ccnum_long;

    public java.lang.String ccnum;

    public int numRows;

    public java.sql.Date currDate;

    public com.acme.validationService.ValidationMessageDocument outboundXMLDoc;

    public com.acme.authorizationService.AuthorizationMessageDocument inboundXMLDoc;

    static final long serialVersionUID = 1L;
    static Random random = new Random();
    static long seed = 1010101;
    static AppLogger logger = new AppLogger("CreditCardValidationProcess");    
    @com.bea.wli.jpd.Callback()
    public Callback callback;
    boolean validCard;        
    private static SimpleDateFormat nodelimeterFormat = new SimpleDateFormat(Parameters.getSProperty("timestamp.format.nodelimeter"));
    /*
     * The area above this comment contains Variable Declarations created from the Design View.
     * The area below this comment contains Control Declarations created from the Design View.
     * 
     * Code in these areas is generated automatically.
     * 
     * 2-Way editing is fully supported in these areas of code.
     * Warning: changing Process Variables and Control Declarations already in use by your application
     * may generate errors in your application if you do not update these declarations
     * in all locations where they are used.
     */
    
    /**
     * @jpd:transform
     */
    @com.bea.wli.jpd.Transform()
    private com.acme.intg.transformations.InboundXMLToOutboundXML toOutboundXML;

    /**
     * @common:control
     */
    @Control()
    private com.acme.intg.controls.CCTxnDBControl ccTxnInsert;

   
    /**
     * This is a control instance, which will be instantiated automatically at
     * runtime.
     * @jpd:transform
     */
    @com.bea.wli.jpd.Transform()
    private com.acme.intg.transformations.CreditCardValidationProcessTransformation transformations1;

    /**
     * @common:context
     */
    @com.bea.wli.jpd.Context()
    JpdContext context; //(..control insertion marker - do not modify this line)
    
    /*
     * The area below this comment contains java methods referenced by communication nodes in the Process Language.
     *
     * Code in this area is generated automatically.
     *
     * 2-Way editing is partially supported in this area of code.
     * Warning: you can safely add code inside a method body but it must be outside of any PROTECTED SECTION
     * block comments. Modifications to code within these comments will prevent you from viewing information
     * in the Design View builder that generated this code.
     */



    public com.acme.validationService.ValidationMessageDocument clientReturn()
    {
        //#START: CODE GENERATED - PROTECTED SECTION - you can safely add code above this comment in this method. #//
        // return
        return outboundXMLDoc;
        //#END  : CODE GENERATED - PROTECTED SECTION - you can safely add code below this comment in this method. #//
    }






    public void clientRequest(com.acme.authorizationService.AuthorizationMessageDocument x0)
    {
        reqAmount = 0;
        availBal = 0;
        validCard = false;
        //#START: CODE GENERATED - PROTECTED SECTION - you can safely add code above this comment in this method. #//
        // input transform
        // parameter assignment
        this.inboundXMLDoc = x0;
        //#END  : CODE GENERATED - PROTECTED SECTION - you can safely add code below this comment in this method. #//
    }





    public void toOutboundXMLConvertInXMLToOutXML() throws Exception
    {
        //#START: CODE GENERATED - PROTECTED SECTION - you can safely add code above this comment in this method. #//
        // input transform
        // return method call
        this.outboundXMLDoc = toOutboundXML.convertInXMLToOutXML(this.inboundXMLDoc);
        // output transform
        // output assignments
        //#END  : CODE GENERATED - PROTECTED SECTION - you can safely add code below this comment in this method. #//
        if (validCard)
        {
            outboundXMLDoc.getValidationMessage().setAuthCode("APRV");
            outboundXMLDoc.getValidationMessage().setRefId(new String("1" +
                                                                      random.nextInt()));
            outboundXMLDoc.getValidationMessage().setProcesstxndate(nodelimeterFormat.format(new java.util.Date()));
            seed++;            
        }
        else
        {
            outboundXMLDoc.getValidationMessage().setAuthCode("DECL");
            outboundXMLDoc.getValidationMessage().setRefId(new String("1" +
                                                                      random.nextInt()));
            outboundXMLDoc.getValidationMessage().setProcesstxndate(nodelimeterFormat.format(new java.util.Date()));            
            seed++;            
        }
        logger.info("toOutboundXML - Begin ");
        logger.info(outboundXMLDoc.getValidationMessage().getCcnum());
        logger.info(outboundXMLDoc.getValidationMessage().getStoreid());
        logger.info(outboundXMLDoc.getValidationMessage().getAmount());
        logger.info(outboundXMLDoc.getValidationMessage().getAuthCode());
        logger.info(outboundXMLDoc.getValidationMessage().getRefId());                
        logger.info("toOutboundXM - End");
    }

    public void ccTxnInsertInsertTxn() throws Exception
    {
        currDate = new java.sql.Date(new java.util.Date().getTime());
        try
        {
        //#START: CODE GENERATED - PROTECTED SECTION - you can safely add code above this comment in this method. #//
        // input transform
            com.acme.intg.transformations.CreditCardValidationProcessTransformation.ccTxnInsertinsertTxnObject obj = transformations1.ccTxnInsertinsertTxn(this.outboundXMLDoc, this.currDate);
        // return method call
            this.numRows = ccTxnInsert.insertTxn(obj.CC_NUM, obj.MERCHANT_ID, obj.AMOUNT, obj.AUTH_CODE, obj.REF_ID, obj.TXN_DATE);
        // output transform
        // output assignments
        //#END  : CODE GENERATED - PROTECTED SECTION - you can safely add code below this comment in this method. #//
        }
        catch (Exception e)
        {
            logger.error("Database Transaction failure");
        }
    }

    public void ccTxnInsertCheckBal() throws Exception
    {
        ccnum_long = Long.parseLong(inboundXMLDoc.getAuthorizationMessage().getCcnum());
        try
        {
        //#START: CODE GENERATED - PROTECTED SECTION - you can safely add code above this comment in this method. #//
        // input transform
        // return method call
            this.availBal = ccTxnInsert.checkBal(this.ccnum_long);
        // output transform
        // output assignments
        //#END  : CODE GENERATED - PROTECTED SECTION - you can safely add code below this comment in this method. #//
            logger.info("Available Balance = " +
                        availBal);
            reqAmount = Long.parseLong(inboundXMLDoc.getAuthorizationMessage().getAmount());
            if (availBal - reqAmount >= 0)
                validCard = true;
        else
            validCard = false;
        } catch (Exception e) {
            validCard=false;             
        }
    }

    public void ccTxnInsertUpdateCCMaster() throws Exception
    {
        try {
        //#START: CODE GENERATED - PROTECTED SECTION - you can safely add code above this comment in this method. #//
        // input transform
        // return method call
        this.numRows = ccTxnInsert.updateCCMaster(this.ccnum_long, this.reqAmount);
        // output transform
        // output assignments
        //#END  : CODE GENERATED - PROTECTED SECTION - you can safely add code below this comment in this method. #//
        } catch (Exception e) {
            validCard=false;   
        }
    }

	@CallbackInterface()
    public interface Callback extends ServiceBrokerControl //(..region end marker - do not modify this line)
    {
    }



    /*
     * Code inserted below this comment is for methods corresponding to Perform or Condition nodes
     * created in the Design View.
     *
     * Feel free to make modifications or add new code here.
     */
    

    public void checkCreditCard() throws Exception
    {
        validCard=true;
    }

    public void logInvalidMessageTypeError() throws Exception
    {
        validCard=false;
        logger.error("Invalid CreditCard Number:"+inboundXMLDoc.getAuthorizationMessage().getCcnum());
    }

    public boolean getValidationCode()
    {
        validCard=true;
		return true;
	}

} 
