/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.utils;

import org.apache.commons.validator.routines.checkdigit.CheckDigitException;
import org.apache.commons.validator.routines.checkdigit.EAN13CheckDigit;

/**
 * Allows the generation of checksums digits.
 * <P>
 * Note: this class uses the EAN13 algorithm to generate the checksum.
 */
public final class ChecksumUtils {

    private final EAN13CheckDigit ean13CheckDigit;

    public ChecksumUtils() {
        ean13CheckDigit = new EAN13CheckDigit();
    }

    /**
     * Generate a single digit checksum for the received number.
     * <P>
     * The input {@code number} should be a decimal number, represented as a string.
     *
     * @param number
     *            the number for which a checksum should be generated.
     * @return a single digit checksum
     */
    public String generate(final String number) {

        validateInput(number);

        try {
            return ean13CheckDigit.calculate(number);
        } catch (CheckDigitException e) {
            throw new IllegalArgumentException("An error occurred when trying to generate a checksum digit for input: "
                + number + ", exception was: " + e);
        }
    }

    /**
     * Validates the checksum of the received number (represented as a string).
     *
     * @param numberWithChecksum
     *            the number (containing a checksum digit at the end) to be validated.
     * @return true if the checksum of the received number is validated, false otherwise.
     */
    public boolean isValid(final String numberWithChecksum) {

        validateInput(numberWithChecksum);

        return ean13CheckDigit.isValid(numberWithChecksum);
    }

    private void validateInput(final String number) {
        if (number == null || number.isEmpty()) {
            throw new IllegalArgumentException("The received input was not an initialized non-null string.");
        }
    }
}
