package hirondelle.web4j.readconfig;

import hirondelle.web4j.util.Regex;

import java.util.regex.Pattern;

final class ParseDecimalFormat {

  /** Used to validate user input of numbers having a decimal point. */
  Pattern getDecimalFormatPattern(String aDecimalSeparator){
    return buildDecimalFormat(aDecimalSeparator);
  }

  // PRIVATE 
  private static final String COMMA = "COMMA";
  private static final String PERIOD = "PERIOD";
  private static final String PERIOD_OR_COMMA = "PERIOD,COMMA";

  /** Return the pattern applicable to numeric input of a number with a possible decimal portion. */
  private Pattern buildDecimalFormat(String aDecimalSeparator){
    String pattern = "";
    String sign = "(?:-|\\+)?";
    String digits = "[0-9]+";
    String decimalSign = getDecimalSignPattern(aDecimalSeparator);
    String places  = "[0-9]+";
    // pattern = sign?(digits|digits.places|.places) 
    pattern = sign + "(" + digits + Regex.OR + digits + decimalSign + places + Regex.OR + decimalSign + places + ")";
    return Pattern.compile(pattern);
  }
 
  private String getDecimalSignPattern(String fDecimalSeparator){
    String result = null;
    if( PERIOD.equalsIgnoreCase(fDecimalSeparator) ) {
      result = "(?:\\.)";
    }
    else if ( COMMA.equalsIgnoreCase(fDecimalSeparator) ){ 
      result = "(?:,)";
    }
    else if ( PERIOD_OR_COMMA.equalsIgnoreCase(fDecimalSeparator)){
      result = "(?:\\.|,)";
    }
    else {
      vomit(
        "In web.xml, the setting for DecimalSeparator is not in the expected format. " + 
        "See web.xml for more information."
      );
    }
    return result;
  }
 
  private void vomit(String aMessage){
    //fLogger.severe(aMessage);
    throw new IllegalArgumentException(aMessage);
  }
}
