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

import cz.moneta.test.dsl.udebs.Udebs;
import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.Endpoint;
import cz.moneta.test.harness.endpoints.udebs.UdebsEndpoint;
import cz.moneta.test.harness.support.data.Generator;

import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;

@SuppressWarnings("all")
public abstract class BasePhoneNumberGenerator implements Generator<String> {

    public String getPhoneNumber(int[] prefices, StoreAccessor harness) {
        return Optional.of(harness.getEndpoint(UdebsEndpoint.class))
                .filter(Endpoint::canAccess)
                .map(e -> getPhoneNumberAndCheckAgainstUdebs(prefices, harness))
                .orElseGet(() -> getRandomPhoneNumber(prefices));
    }

    protected String getPhoneNumberAndCheckAgainstUdebs(int[] prefixArray, StoreAccessor harness) {
        return Stream.generate(() -> getRandomPhoneNumber(prefixArray))
                .filter(gn -> !new Udebs(harness)
                        .phone()
                        .existPhone(gn)
                )
                .findFirst()
                .get();
    }

    private String getRandomPhoneNumber(int[] prefixArray) {
        long prefix = prefixArray[ThreadLocalRandom.current().nextInt(prefixArray.length)];
        long tail = ThreadLocalRandom.current().nextLong(1000000);
        return String.format("%d%06d", prefix, tail);
    }
}