/*
 * Copyright (c) eHealth
 */
package be.fgov.ehealth.technicalconnector.jca.proxy;

import static be.ehealth.technicalconnector.utils.ConnectorIOUtils.closeQuietly;

import java.security.Security;
import java.security.SignatureException;
import java.security.cert.X509Certificate;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.Validate;

import be.ehealth.technicalconnector.beid.BeIDCardFactory;
import be.fedict.commons.eid.client.BeIDCard;
import be.fedict.commons.eid.client.FileType;
import be.fedict.commons.eid.client.impl.BeIDDigest;
import be.fedict.commons.eid.jca.BeIDProvider;
import be.fgov.ehealth.technicalconnector.distributedkeys.DistributedSignerProxy;


/**
 * Proxy class for BeID
 *
 * @author EHP
 */
public class BeIDDistributedSigner implements DistributedSignerProxy {

    @Override
    public byte[] sign(byte[] digestValue, String digestAlgo, String alias) throws SignatureException {
        BeIDDigest digest = null;
        for (BeIDDigest beEidDigest : BeIDDigest.values()) {
            if (beEidDigest.getStandardName()
                           .equalsIgnoreCase(digestAlgo)) {
                digest = beEidDigest;
                break;
            }
        }
        FileType type = getFileType(alias);

        Validate.notNull(digest);
        try {
            Security.addProvider(new BeIDProvider());
            BeIDCard card = BeIDCardFactory.getBeIDCard();
            return card.sign(digestValue, digest, type, false);
        } catch (Exception e) {
            throw new SignatureException(e);
        }
    }

    /**
     * @param alias
     * @return
     */
    private FileType getFileType(String alias) {
        FileType type = null;
        if ("Authentication".equalsIgnoreCase(alias)) {
            type = FileType.AuthentificationCertificate;
        } else if ("Signature".equalsIgnoreCase(alias)) {
            type = FileType.NonRepudiationCertificate;
        }
        Validate.notNull(type);
        return type;
    }

    /**
     * @see be.fgov.ehealth.technicalconnector.distributedkeys.DistributedSignerProxy#getAliases()
     */
    @Override
    public Set<String> getAliases() {
        Set<String> result = new HashSet<String>();
        result.add("Authentication");
        result.add("Signature");
        return result;
    }

    /**
     * @see be.fgov.ehealth.technicalconnector.distributedkeys.DistributedSignerProxy#getCertificateChain(java.lang.String)
     */
    @Override
    public List<X509Certificate> getCertificateChain(String alias) {
        BeIDCard card = null;
        try {
            Security.addProvider(new BeIDProvider());
            card = BeIDCardFactory.getBeIDCard();
            return card.getCertificateChain(getFileType(alias));
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        } finally {
            closeQuietly(card);
        }
    }
}
