/*
 *     Copyright (C) 2015 ASIP Santé
 */
package fr.asipsante.mss.connectkit.connection;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextOutputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;

/**
 * {@link CallbackHandler} utilisée pour la saisie de mot de passe de keystore.
 * 
 * @author ASIP Santé
 *
 */
final class Pkcs11CallbackHandler implements CallbackHandler {
    @Override
    public void handle(Callback[] callbacks) throws IOException,
            UnsupportedCallbackException {
        for (Callback cb : callbacks) {
            System.out.println("Pkcs11 callback handler.");
            if (cb instanceof TextOutputCallback) {
                TextOutputCallback textOutputCallback = (TextOutputCallback) cb;
                int messageType;
                switch (textOutputCallback.getMessageType()) {
                case TextOutputCallback.INFORMATION:
                    messageType = JOptionPane.INFORMATION_MESSAGE;
                    break;
                case TextOutputCallback.WARNING:
                    messageType = JOptionPane.WARNING_MESSAGE;
                    break;
                case TextOutputCallback.ERROR:
                    messageType = JOptionPane.ERROR_MESSAGE;
                default:
                    messageType = JOptionPane.PLAIN_MESSAGE;
                    break;
                }
                JOptionPane.showMessageDialog(null,
                        textOutputCallback.getMessage(),
                        "Authentification PKCS11", messageType);
            } else if (cb instanceof PasswordCallback) {

                PasswordCallback passwdCallback = (PasswordCallback) cb;

                JPasswordField jpf = new JPasswordField(4);
                JLabel jl = new JLabel("Code Porteur");
                Box box = Box.createHorizontalBox();
                box.add(jl);
                box.add(jpf);
                int x = JOptionPane.showConfirmDialog(null, box,
                        "Saisissez votre Code Porteur",
                        JOptionPane.OK_CANCEL_OPTION);
                char[] pw = null;
                if (x == JOptionPane.OK_OPTION) {
                    pw = jpf.getPassword();
                    passwdCallback.setPassword(pw);
                    return;
                }
                throw new IOException(
                        "Erreur dans le saisie du Code Porteur (opération annulée?).");
            } else {
                throw new UnsupportedCallbackException(cb,
                        "Seuls messagestexte et password prompt sont supportés.");
            }
        }
    }
}