/*
 * Copyright (c) eHealth
 */
package be.fgov.ehealth.technicalconnector.signature.impl;

import be.ehealth.technicalconnector.exception.TechnicalConnectorException;
import be.ehealth.technicalconnector.service.sts.security.Credential;
import be.ehealth.technicalconnector.service.sts.security.impl.BeIDCredential;
import be.ehealth.technicalconnector.session.Session;
import be.ehealth.technicalconnector.session.SessionItem;
import be.ehealth.technicalconnector.session.SessionManager;
import be.fgov.ehealth.technicalconnector.signature.AdvancedElectronicSignatureEnumeration;
import be.fgov.ehealth.technicalconnector.signature.SignatureBuilderFactory;
import be.fgov.ehealth.technicalconnector.signature.domain.CadesOption;
import be.fgov.ehealth.technicalconnector.signature.domain.SignatureVerificationError;
import be.fgov.ehealth.technicalconnector.tests.utils.AssumeTools;
import org.junit.BeforeClass;
import org.junit.Test;

import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static be.ehealth.technicalconnector.service.sts.security.impl.BeIDCredential.EID_AUTH_ALIAS;


/**
 * tests the SignatureBuilder.
 *
 * @author EHP
 */
public class CadesBesSignatureTest extends AbstractSignatureTest {


    @BeforeClass
    public static void initBuilder() throws Exception {
        builder = SignatureBuilderFactory.getSignatureBuilder(AdvancedElectronicSignatureEnumeration.CAdES);
    }

    private byte[] generateCadesBes(Map<String, Object> options) throws TechnicalConnectorException {
        options.put(CadesOption.ENCAPSULATE, Boolean.TRUE);
        return builder.sign(credential, textToSign, options);
    }

    @Test
    public void testValidateGeneratedCadesBes() throws Exception {
        Map<String, Object> options = new HashMap<String, Object>();
        verifyCades(generateCadesBes(options), textToSign);
    }

    @Test
    public void testValidateGeneratedCadesBesWithDefaultSignatureAlgorithm() throws Exception {
        verifyCades(generateCadesBes(new HashMap<>()), textToSign);
    }

    @Test
    public void alteredCadesBes() throws Exception {
        Map<String, Object> options = new HashMap<>();
        options.put(CadesOption.ENCAPSULATE, Boolean.TRUE);
        byte[] signature = builder.sign(credential, textToSign, options);
        verifyCades(signature, textToSign_bis, SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
    }

    @Test
    public void testWithEid() throws Exception {
        AssumeTools.isEIDEnabled();
        Credential beid = BeIDCredential.getInstance("test", BeIDCredential.EID_AUTH_ALIAS);
        Map<String, Object> options = new HashMap<>();
        options.put(CadesOption.ENCAPSULATE, Boolean.TRUE);
        byte[] signature = builder.sign(beid, textToSign, options);
        verifyCades(signature, textToSign);
    }

}
