/*******************************************************************************
 * Copyright 2019 2Fi Business Solutions Ltd.
 *
 * This code is part of the Core project.
 *
 * This code is copyrighted. Under no circumstances should any party, people,
 * or organization should redistribute any portions of this code in any form,
 * either verbatim or through electronic media, to any third parties, unless
 * under explicit written permission by 2Fi Business Solutions Ltd.
 ******************************************************************************/
package com.ffii.core.utils;

/**
 * CheckDigitUtils
 *
 * @author Patrick
 */
public abstract class CheckDigitUtils {

	/*
	 * ISO/IEC 7812-1 Annex B
	 * Check digit calc method
	 */
	public static int luhnCalc(String digitsString) {
		int sum = 0;
		boolean alternate = false;
		for (int i = 0; i < digitsString.length(); i++) {
			int n = Integer.parseInt(digitsString.substring(i, i + 1));
			if (alternate) {
				n *= 2;
				if (n > 9) {
					n = (n % 10) + 1;
				}
			}
			sum += n;
			alternate = !alternate;
		}
		return ((sum * 9) % 10);
	}

	/*
	 * ISO/IEC 7812-1 Annex B
	 * Check digit check method
	 */
	public static boolean luhnCheck(String digitsStringWithCheckDigit) {
		int sum = 0;
		boolean alternate = false;
		for (int i = digitsStringWithCheckDigit.length() - 1; i >= 0; i--) {
			try {
				int n = Integer.parseInt(digitsStringWithCheckDigit.substring(i, i + 1));
				if (alternate) {
					n *= 2;
					if (n > 9) {
						n = (n % 10) + 1;
					}
				}
				sum += n;
				alternate = !alternate;
			} catch (NumberFormatException nfe) {
				continue;
			}
		}
		return (sum % 10 == 0);
	}

}
