package genepi.imputationserver.util;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.RandomStringUtils;

public class PasswordCreator {

	public static String createPassword() {
		return createPassword(5, 5, 2, 2, 3);
	}

	public static String createPassword(int uppercaseLetters, int lowercaseLetters, int numbers, int symbols,
			int duplicates) {

		String pwd = null;

		do {
			String upper = RandomStringUtils.random(uppercaseLetters, 0, 0, true, false, null, new SecureRandom())
					.toUpperCase();

			String lower = RandomStringUtils.random(lowercaseLetters, 0, 0, true, false, null, new SecureRandom())
					.toLowerCase();

			String number = RandomStringUtils.random(numbers, 0, 0, false, true, null, new SecureRandom())
					.replaceAll("\\s+", "");

			String symbol = RandomStringUtils.random(symbols, 33, 127, false, false, null, new SecureRandom());
			
			// exclude non password-friendly symbols (quotes and ^)
			symbol = symbol.replaceAll((char) 39 + "", "").replaceAll((char) 94 + "", "").replaceAll((char) 96 + "",
					"");

			pwd = shuffleAndCheck(upper + lower + number + symbol, duplicates);

		} while (pwd == null);

		return pwd;

	}

	private static String shuffleAndCheck(String input, int duplicates) {
		List<Character> characters = new ArrayList<Character>();
		int countDuplicates = 0;
		for (char c : input.toCharArray()) {
			if (characters.contains(c)) {
				countDuplicates++;
			}
			characters.add(c);
		}
		if (countDuplicates >= duplicates) {
			return null;
		}

		StringBuilder pwd = new StringBuilder(input.length());
		while (characters.size() != 0) {
			int randPicker = (int) (Math.random() * characters.size());
			pwd.append(characters.remove(randPicker));
		}
		return pwd.toString();
	}

}
@@ -933,19 +933,16 @@
 dom());%0A
-%09%09%09
 %0A%09%09%09// e
@@ -981,23 +981,8 @@
 bols
- (quotes and %5E)
 %0A%09%09%09
@@ -1012,21 +1012,10 @@
 All(
-(char) 39 + 
 %22
+'
 %22, %22
@@ -1032,27 +1032,63 @@
 All(
-(char) 94 + %22%22, %22%22)
+%22%5C%22%22, %22%22).replaceAll(%22%5E%22, %22%22).replaceAll(%22,%22, %22%22)%0A%09%09%09%09%09
 .rep
@@ -1110,22 +1110,17 @@
 96 + %22%22,
-%0A%09%09%09%09%09
+ 
 %22%22);%0A%0A%09%09

remove non password-friendly characters