package cokr.xit.ens.core.utils;

import net.bytebuddy.utility.RandomString;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

public class IdGenerator {

    private static AtomicReference<Long> currentTime = new AtomicReference<>(System.currentTimeMillis());

    public static Long getCurrentTimeMs() {
        Long prev;
        Long next = System.currentTimeMillis();
        do {
            prev = currentTime.get();
            next = next > prev ? next : prev + 1;
        } while (!currentTime.compareAndSet(prev, next));
        return next;
    }

    public static Long getCurrentTimeSec() {
        return IdGenerator.getCurrentTimeMs() / 1000L;
    }

    public static String getRandomString(int length) {
        return RandomString.make(length);
    }

    public static String getUUID() {
        return UUID.randomUUID().toString();
    }

    public static String getUUID(String prefix) {
        return prefix + "-" + getUUID();
    }

    public static String getUUID(String prefix, String postfix) {
        return getUUID(prefix) + "-" + postfix;

    }

    private static AtomicLong atomicCounter = new AtomicLong();

    public static String getUUIDwithCount() {
        String currentCounter = String.valueOf(atomicCounter.getAndIncrement());
        String uniqueId = UUID.randomUUID().toString();

        return uniqueId + "-" + currentCounter;
    }

    public static String getUUIDwithCount(String prefix) {
        return prefix + "-" + getUUIDwithCount();
    }

    public static String getUUIDwithCount(String prefix, String postfix) {
        return getUUIDwithCount(prefix) + "-" + postfix;
    }

    public static String getShortUUID() {
        UUID u = UUID.randomUUID();
        return toIDString(u.getMostSignificantBits()) + toIDString(u.getLeastSignificantBits());
    }

    public static String getShortUUID(String prefix) {
        return prefix + "-" + getShortUUID();
    }

    public static String getShortUUID(String prefix, String postfix) {
        return getShortUUID(prefix) + "-" + postfix;
    }

    private static String toIDString(long i) {
        char[] buf = new char[32];
        int z = 64;
        int cp = 32;
        long b = z - 1;
        do {
            buf[--cp] = DIGITS66[(int) (i & b)];
            i >>>= 6;
        } while (i != 0);
        return new String(buf, cp, (32 - cp));
    }

   
    private final static char[] DIGITS66 = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '-', '.', '_', '~'
    };
}
