package com.atlassian.bitbucket.installer;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class PasswordGenerator {

    private static final String LOWERCASE_ALPHAS = "abcdefghijklmnopqrstuvwxyz";
    private static final String UPPERCASE_ALPHAS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String INTEGERS = "1234567890";
    private static final String SPECIALS = "!#$%*";
    private static final String DEFAULT_ALGORITHM = "SHA1PRNG";
    private static final String ALL_CHARACTERS = LOWERCASE_ALPHAS + UPPERCASE_ALPHAS + INTEGERS + SPECIALS;

    public static String newPassword() throws NoSuchAlgorithmException {
        return newPassword(DEFAULT_ALGORITHM);
    }

    public static String newPassword(String algorithm) throws NoSuchAlgorithmException {
        SecureRandom random = SecureRandom.getInstance(algorithm);

        StringBuilder buffer = new StringBuilder();

        // Ensure there is at least one of each type of character
        buffer.append(LOWERCASE_ALPHAS.charAt(random.nextInt(LOWERCASE_ALPHAS.length())));
        buffer.append(UPPERCASE_ALPHAS.charAt(random.nextInt(UPPERCASE_ALPHAS.length())));
        buffer.append(INTEGERS.charAt(random.nextInt(INTEGERS.length())));
        buffer.append(SPECIALS.charAt(random.nextInt(SPECIALS.length())));

        // Get another 12 random characters from the all character list
        for (int i = 0; i < 12; i++) {
            buffer.append(ALL_CHARACTERS.charAt(random.nextInt(ALL_CHARACTERS.length())));
        }

        return buffer.toString();
    }
}
