package cz.moneta.test.dsl.util.data.generators;

import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.support.data.Generator;

import java.math.BigInteger;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;

public class SipoGenerator implements Generator<String> {

    private static final int CHECKSUM_ROOT = 373173173;

    public String generate(StoreAccessor harness, Object... params) {
        final int base = ThreadLocalRandom.current().nextInt(1_000_000_000);

        Integer checkSum = IntStream.range(0, 9).boxed()
                .reduce(0, (acc, i) -> acc + getDigit(CHECKSUM_ROOT, i) * getDigit(base, i));

        Integer checkDigit = Optional.of(checkSum)
                .map(i -> i % 10)
                .filter(i -> i > 0)
                .map(i -> 10 - i)
                .orElse(0);

        return String.format("%09d%d", base, checkDigit);
    }

    private static int getDigit(int number, Integer digitIndex) {
        return BigInteger.valueOf(number)
                .divide(BigInteger.TEN.pow(digitIndex))
                .mod(BigInteger.TEN)
                .intValue();
    }
}
