package cn.quantgroup.xyqb.util;

import java.security.SecureRandom;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.UUID;

/**
 * Created by hechao on 2020/2/13.
 */
public abstract class RandomSequencer {

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final SecureRandom RANDOM = new SecureRandom();

    public static String randomNumber() {
        char[] chars = new char[32];
        for (int index = 0; index < chars.length; ++index) {
            chars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(chars);
    }

    public static int next() {
        return next(3, 0, 0);
    }

    public static int next(int size, int zeros) {
        return next(size, zeros, 0);
    }

    public static int next(int size, int zeros, int minimum) {
        int s = (int) (System.nanoTime() % (int) Math.pow(10, size));
        return Math.max(s - (s % (int) Math.pow(10, zeros)), minimum);
    }

    public static long randomUUID(Long id) {
        UUID uuid = UUID.randomUUID();
        String most = Long.toHexString(uuid.getMostSignificantBits());
        String least = Long.toHexString(uuid.getLeastSignificantBits());
        return id ^ Long.parseLong(most.substring(0, 8), 16) * 31L
                ^ Long.parseLong(least.substring(0, 4), 16) * 31L
                ^ Long.parseLong(most.substring(8, 12), 16) * 31L
                ^ Long.parseLong(least.substring(4), 16) * 31L
                ^ Long.parseLong(most.substring(12), 16) * 31L;
    }

    //number
    public static String hexUUID(Long id) {
//        return Long.toHexString(id) + Long.toHexString(UUID.randomUUID().getMostSignificantBits());
        Long uuid = randomUUID(id);
        return new StringBuilder().append(Long.toHexString(id & 0xFFFFFFFFL)).append(Long.toHexString(uuid)).append(Long.toHexString(id >> 32)).toString();
    }

    public static String decUUID(Long id) {
        LocalDate date = LocalDate.now();
        long time = (long) date.getYear() * 10000L;
        time = time + ((long) date.getMonthValue() * 100L);
        time = (time + (long) date.getDayOfMonth()) * 100000L + (long) LocalTime.now().toSecondOfDay();
        return new StringBuilder().append(time).append(randomUUID(id)).toString();
    }

    public static void main(String[] args) {
        long id = 255255255255L ^ 8000L;
        SnowflakeIdentitySequencer snowflakeIdWorker = new SnowflakeIdentitySequencer(id, 8);
        String decUUID = RandomSequencer.decUUID(snowflakeIdWorker.nextId());
        System.out.println(decUUID);

        System.out.println(RandomSequencer.next(3, 0));
    }
}