/*
 * Copyright 2013 - Scriptel Corporation
 */
package com.scriptel.easyscript;

import java.util.EnumSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class attempts to identify credit card issuers based on patterns in the
 * numbers each vendor issues.
 */
public enum FinancialCardIssuer {
    AMERICAN_EXPRESS ("American Express","^(34|37)\\d{13}$"),
    DINERS_CLUB ("Diners Club","^(30[0-5]\\d{11}|36\\d{12})$"),
    CARTE_BLANCH ("Carte Blanche","^38\\d{12}$"),
    DISCOVER ("Discover","^6011\\d{12}$"),
    ENROUTE ("EnRoute","^(2131|1800)\\d{11}$"),
    JCB ("JCB","^(3\\d{15}|(2131|1800)\\d{11})$"),
    MASTER_CARD ("Master Card","^5[1-5]\\d{14}$"),
    VISA ("Visa","^4\\d{12,15}$"),
    UNKNOWN ("Unknown",".*");
    
    private String issuerName;
    private String regex;
    
    /**
     * Constructor, creates a new instance of this enum.
     * @param issuerName Human-friendly name of the issuer.
     * @param regex Regular expression needed to identify the card.
     */
    FinancialCardIssuer(String issuerName, String regex) {
        this.issuerName = issuerName;
        this.regex = regex;
    }
    
    /**
     * This method attempts to identify the issuer of a credit card based on
     * a credit card number.
     * @param number Number to inspect.
     * @return Issuer if identified, UNKNOWN otherwise.
     */
    public static FinancialCardIssuer identifyByCardNumber(String number) {
        for(FinancialCardIssuer i : EnumSet.allOf(FinancialCardIssuer.class)) {
            Matcher m = i.getRegex().matcher(number);
            if(m.find()) {
                return i;
            }
        }
        return UNKNOWN;
    }

    /**
     * Gets the issuer name.
     * @return Human-friendly issuer name.
     */
    public String getIssuerName() {
        return issuerName;
    }

    /**
     * Gets the regular expression string.
     * @return Regular expression string.
     */
    public String getRegexString() {
        return regex;
    }
    
    /**
     * This method gets the regular expression pattern used to match the card
     * number for this member.
     * @return Regular expression pattern.
     */
    public Pattern getRegex() {
        return Pattern.compile(regex);
    }
}
