package cn.iocoder.yudao.framework.common.thealgorithms.others;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * Creates a random password from ASCII letters Given password length bounds
 *
 * @author AKS1996
 * @date 2017.10.25
 */
final class PasswordGen {
    private PasswordGen() {
    }

    static String generatePassword(int minLength, int maxLength) {
        Random random = new Random();

        String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String lower = "abcdefghijklmnopqrstuvwxyz";
        String numbers = "0123456789";
        String specialChars = "!@#$%^&*(){}?";

        String allChars = upper + lower + numbers + specialChars;

        List<Character> letters = new ArrayList<Character>();
        for (char c : allChars.toCharArray()) {
            letters.add(c);
        }

        // Inbuilt method to randomly shuffle a elements of a list
        Collections.shuffle(letters);
        StringBuilder password = new StringBuilder();

        // Note that size of the password is also random
        for (int i = random.nextInt(maxLength - minLength) + minLength; i > 0; --i) {
            password.append(letters.get(random.nextInt(letters.size())));
        }

        return password.toString();
    }
}
