package com.programming.interview;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FIDChecker {
public static String checkFID(String strFID, String entityType ){
String returnFID = "INVALID FID/ENTITY TYPE";
entityType = ("P".equalsIgnoreCase(entityType)||"B".equalsIgnoreCase(entityType))? entityType:null;
if(null!=strFID && null!= entityType)
{
if (validateFID(strFID, entityType))
{
returnFID = reformatFID(strFID, entityType);
}
}
return returnFID;
}
private static boolean validateFID(String strFID, String entityType){
boolean isValidFID = false;
String validFormat1 = null;
String validFormat2 = null;
if ("P".equalsIgnoreCase(entityType))
{
validFormat1 = "\\d{3}-?\\d{2}-?\\d{4}";
validFormat2 = "\\d{3}\\s?\\d{2}\\s?\\d{4}";
}
else if ("B".equalsIgnoreCase(entityType))
{
validFormat1 = "\\d{2}-?\\d{7}";
validFormat2 = "\\d{2}\\s?\\d{7}";
}
Pattern matchingPattern1 = Pattern.compile(validFormat1);
Matcher patternMatcher1 = matchingPattern1.matcher(strFID);
Pattern matchingPattern2 = Pattern.compile(validFormat2);
Matcher patternMatcher2 = matchingPattern2.matcher(strFID);
if (patternMatcher1.matches() || patternMatcher2.matches())
{
isValidFID = true;
}
return isValidFID;
}
private static String reformatFID(String strFID, String entityType){
String plainFID = strFID.replaceAll("[-\\s]", "");
StringBuffer formattedFID = new StringBuffer();
if("P".equalsIgnoreCase(entityType))
{
formattedFID.append(plainFID.substring(0, 3));
formattedFID.append("-");
formattedFID.append(plainFID.substring(3, 5));
formattedFID.append("-");
formattedFID.append(plainFID.substring(5, 9));
}
else if ("B".equalsIgnoreCase(entityType))
{
formattedFID.append(plainFID.substring(0, 2));
formattedFID.append("-");
formattedFID.append(plainFID.substring(2, 9));
}
return formattedFID.toString();
}
}