package com.avaya.ocp.openinterfaces.ws;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.jws.WebService;

@WebService(portName="EmailOpenInterfacesServicePort", 
serviceName = "EmailOpenInterfacesServiceService", 
targetNamespace = "http://ws.openinterfaces.ocp.avaya.com/", 
endpointInterface = "com.avaya.ocp.openinterfaces.ws.IEmailOpenInterfacesService")
public class EmailOpenInterfacesService implements IEmailOpenInterfacesService{
 
	private String CreditCardPattern = "^(?:(?<visa>4[0-9]{12}(?:[0-9]{3})?)|" +
	        "(?<mastercard>5[1-5][0-9]{14})|" +
	        "(?<discover>6(?:011|5[0-9]{2})[0-9]{12})|" +
	        "(?<amex>3[47][0-9]{13})|" +
	        "(?<diners>3(?:0[0-5]|[68][0-9])?[0-9]{11})|" +
	        "(?<jcb>(?:2131|1800|35[0-9]{3})[0-9]{11}))$";
	
  
  /// <summary>
  /// Input array:
  ///     [0]: Subject
  ///     [1]: Plain text Body of email
  /// Output array:
  ///     [0]: Subject
  ///     [1]: Plain text Body of email
  /// </summary>
  /// <param name="inputParameters"></param>
  /// <returns></returns>
  public String[] MaskCreditCardNumber(String[] inputParameters)
  {
      String[] outputParameters = new String[2];

      if (inputParameters != null && inputParameters[0] != null && inputParameters[1] != null)
      {
          try{
              outputParameters[0] = DetectCreditCardNumber(inputParameters[0]);
              outputParameters[1] = DetectCreditCardNumber(inputParameters[1]);
          }
          catch (Exception e)
          {
              outputParameters[0] = inputParameters[0];
              outputParameters[1] = inputParameters[1];
          }
      }

      return outputParameters;
  }
  

  private String DetectCreditCardNumber(String input){
	  String output = null;

      try{
    	  Pattern pattern = Pattern.compile(CreditCardPattern);
    	    //Strip all hyphens
    	    input = input.replaceAll("-", "");
    	    //Match the card
    	    Matcher matcher = pattern.matcher(input);

          if (matcher.matches())
          {
              output = ScrubCreditCard(matcher, input);
          }
          else
          {
              output = input;
          }
      }
      catch (Exception e)
      {
          output = input;
      }


      return output;
  }
  
  private String ScrubCreditCard(Matcher match, String input)
  {
      String output = input;
      Pattern pattern = Pattern.compile(CreditCardPattern);
      output = pattern.matcher(input).replaceAll("++++++++++++++++++++");

      return output;
  }
}
