/*
 * 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.config.cli;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.Map;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.BeforeClass;
import org.junit.Test;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.certificates.bean.X509CertificateType;
import com.scytl.cryptolib.primitives.primes.utils.PemUtils;
import com.scytl.cryptolib.scytl.keystore.cryptoapi.CryptoAPIScytlKeyStore;
import com.scytl.products.ov.config.utils.ChainValidator;
import com.scytl.products.ov.utils.KeyStoreLoader;
import com.scytl.products.ov.utils.PasswordReaderUtils;

import mockit.Mock;
import mockit.MockUp;

public class CertificateCommandTest {

    public static final String OUTPUT_PATH = "target/certificateCSR/";

    public static final char[] ROOT_PASSWORD = "1111111111111111".toCharArray();

    public static final String PRIVATE_KEY_ALIAS = "privatekey";

    private static final String ROOT_KS_PATH = "src/test/resources/testMaterial/platformRoot/swisspostRootCA.sks";

    private static final String CSR_PATH = "src/test/resources/testMaterial/tenantCSR/tenant_manolo_CSR.pem";

    private static Map<String, String> params2values;

    private CertificateCommand _sut;

    @BeforeClass
    public static void setUp() {

        Security.addProvider(new BouncyCastleProvider());

        String[] inputParams = {"-out", OUTPUT_PATH, "-ks", ROOT_KS_PATH, "-csr", CSR_PATH };
        params2values = Action.CERT_TENANT.validateAndArrange(inputParams);

    }

    @Test
    public void certificateTheTenant() throws IOException, GeneralCryptoLibException, CertificateException {

        _sut = new CertificateCommand();

        new MockUp<PasswordReaderUtils>() {

            @Mock
            public char[] readPasswordFromConsole() {
                return "1111111111111111".toCharArray();
            }
        };

        _sut.execute(params2values);

        Path pathCertificate = Paths.get(OUTPUT_PATH, "tenant_manolo.pem");

        Certificate certificate =
            PemUtils.certificateFromPem(new String(Files.readAllBytes(pathCertificate), StandardCharsets.UTF_8));
        CryptoAPIScytlKeyStore rootKeyStore =
            KeyStoreLoader.loadPlatformRootKeyStore(Paths.get(ROOT_KS_PATH), ROOT_PASSWORD);
        Certificate platformRootCA = rootKeyStore.getCertificateChain(PRIVATE_KEY_ALIAS)[0];

        ChainValidator.validateChain(platformRootCA, certificate, X509CertificateType.CERTIFICATE_AUTHORITY);

    }

}
