/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.utils;

import java.io.Console;
import java.util.Arrays;

import com.scytl.products.ov.config.exceptions.specific.PasswordReaderUtilsException;

/**
 * Provides utilities to read passwords.
 */
public class PasswordReaderUtils {
    
	/**
     * Non-public constructor
     */
	private PasswordReaderUtils() {
    }
	
	/**
     * Reads a password twice in order to confirm that the user wrote it correctly.
     * <p>
     * Note that this method is to be used when asking a password to the user when creating a Keystore.
     * </p>
     */
    public static char[] readPasswordFromConsoleAndConfirm() {

        Console console = getConsole();

        boolean noMatch;
        char[] password1;
        char[] password2;
        do {
            password1 = console
                .readPassword("Please choose a password for the keystore (it must contain at least 16 characters): ");
            password2 = console.readPassword("Enter the password again: ");
            noMatch = !Arrays.equals(password1, password2);
            if (noMatch) {
                console.format("Passwords don't match. Try again.%n");
            } else {
                console.format("Password correctly set.%n");
            }
        } while (noMatch);

        Arrays.fill(password2, '\u0000');
        return password1;
    }

    /**
     * Reads a keystore password from the console for a particular tenant and a particular service.
     *
     * @param tenantID
     *            the tenant.
     * @param service
     *            the service.
     * @return the entered password as an array of type 'char'.
     */
    public static char[] readKeystorePasswordFromConsole(final String tenantID, final String service) {
        Console console = getConsole();
        return console.readPassword(
            "Please enter the system keystore password for tenant " + tenantID + " for service " + service + ": ");
    }

    /**
     * Reads a password from console.
     * <p>
     * Note that this method is to be used when asking a password to the user when opening a Keystore.
     * </p>
     */
    public static char[] readPasswordFromConsole() {
        Console console = getConsole();
        return console.readPassword("Enter your password: ");
    }

    private static Console getConsole() {
        Console console = System.console();
        if (console == null) {
            throw new PasswordReaderUtilsException("No console was found");
        }
        return console;
    }
}
