package oracle.apps.aia.demo;

import oracle.integration.platform.faultpolicy.IFaultRecoveryContext;
import com.collaxa.cube.engine.fp.BPELFaultRecoveryContextImpl;
import com.collaxa.cube.engine.types.bpel.CXMessageVariable;
import oracle.apps.aia.core.eh.IAIAErrorHandlerExtension;
import oracle.apps.aia.core.eh.logging.AIALogger;

public class AIADemoErrorHandlerExtImpl implements IAIAErrorHandlerExtension
{

    public AIADemoErrorHandlerExtImpl()
    {
    }

    public String handleBusinessError( String faultMessageConstructed )
    {
        System.out.println( "### Invoked AIADemoErrorHandlerExtImpl->handleBusinessError" );
        // Doing nothing so far
        return faultMessageConstructed;
    }
    
    public String handleCompositeSystemError(IFaultRecoveryContext iFaultRecoveryContext,
                                             String faultMessageConstructed,
                                             String componentType){

      System.out.println( "### Invoked AIADemoErrorHandlerExtImpl->handleCompositeSystemError" );
      String enrichedFaultMessageConstructed = faultMessageConstructed;

      if ( componentType.equals("bpel") ) {
        System.out.println( "### AIADemoErrorHandlerExtImpl: BPEL fault handler extension");
        try
        {
            BPELFaultRecoveryContextImpl bpelCtx = (BPELFaultRecoveryContextImpl) iFaultRecoveryContext;

            CXMessageVariable bpelVar = (CXMessageVariable) bpelCtx.getVariableData( "AIADemoProcessCreditChargeAuthorizationReqMsg" );

            if (bpelVar == null) {
              System.out.println( "### AIADemoErrorHandlerExtImpl: Could not get BPEL Variable AIADemoProcessCreditChargeAuthorizationReqMsg");
            } else {

              String ebmPayload = bpelVar.toXML();
              ebmPayload = ebmPayload.replaceFirst("part [0]","");
              enrichedFaultMessageConstructed = 
                    faultMessageConstructed.replaceFirst( "<IntermediateMessageHop>", ( new StringBuilder() ).append( "<InputPayLoad>" ).append( ebmPayload ).append( "</InputPayLoad><IntermediateMessageHop>" ).toString() );
            }
        }
        catch ( Exception ex )
        {
            ex.printStackTrace();
            AIALogger.logErrorMessage( null, ex.getLocalizedMessage() );
        }
      } else if ( componentType.equals("mediator") ) {
        System.out.println( "### AIADemoErrorHandlerExtImpl: Mediator fault handler extension");
      }
      
      return enrichedFaultMessageConstructed;
    }

}

