package cz.muni.fi.rtc.teacherWorkbench.importer;

import java.util.Collection;
import java.util.Random;

import cz.muni.fi.rtc.teacherWorkbench.importer.exceptions.EmptyPossibleCharsException;
import cz.muni.fi.rtc.teacherWorkbench.model.ImportedPerson;

/**
 * Password generator
 * @author Jan Stastny
 *
 */
public class PasswordGenerator {

	public static final int DEFAULT_LENGTH = 7;
	
	private char[] possibleChars = new char[]{'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',
            '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
	
	private Random seed = new Random();
	
	/**
	 * Creates new password generator. All alpha numeric values are possible for the password
	 */
	public PasswordGenerator() {
	}
	
	/**
	 * Generates new password generator. 
	 * @param possible Array of chars the password will be generated from
	 */
	public PasswordGenerator(char[] possible) {
		this.possibleChars = possible;
	}
	
	/**
	 * Generates random password of given length
	 * @param length Password length
	 * @return Random password
	 * @throws EmptyPossibleCharsException if the array of possible chars is empty
	 */
	public String generatePassword(int length) throws EmptyPossibleCharsException {
		if(possibleChars.length < 1) {
			throw new EmptyPossibleCharsException("possibleChars array is empty");
		}
		StringBuffer passwordBuffer = new StringBuffer();
		for(int i=0; i < length; i++) {
			passwordBuffer.append(possibleChars[seed.nextInt(possibleChars.length)]);
		}
		return passwordBuffer.toString();
	}
	
	/**
	 * Generates password of default length.
	 * Default length is taken from DEFAULT_LENGTH constant
	 * @return Random password
	 * @throws EmptyPossibleCharsException if the array of possible chars is empty 
	 */
	public String generatePassword() throws EmptyPossibleCharsException {
		return generatePassword(DEFAULT_LENGTH);
	}
	
	
	/**
	 * Generates passwords for the users.
	 * @param people People to have password generated
	 * @return People with generated passwords
	 */
	public static Collection generatePasswordsForPeople(Collection people) {
		PasswordGenerator generator = new PasswordGenerator();
		for(ImportedPerson person: people) {
			person.setRawPassword(generator.generatePassword());
		}
		return people;
	}
	
}