/*
 * 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.sdm.application.service;

import static java.nio.file.Files.createTempFile;
import static java.nio.file.Files.deleteIfExists;
import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.nio.file.Path;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
import java.util.Date;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.scytl.cryptolib.api.asymmetric.AsymmetricServiceAPI;
import com.scytl.cryptolib.api.certificates.CertificatesServiceAPI;
import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.asymmetric.service.AsymmetricService;
import com.scytl.cryptolib.certificates.bean.RootCertificateData;
import com.scytl.cryptolib.certificates.bean.ValidityDates;
import com.scytl.cryptolib.certificates.bean.X509DistinguishedName;
import com.scytl.cryptolib.certificates.cryptoapi.CryptoAPIX509Certificate;
import com.scytl.cryptolib.certificates.service.CertificatesService;
import com.scytl.products.ov.commons.path.PathResolver;

/**
 * Tests of {@link PlatformRootCAService}.
 */
public class RootCAServiceTest {
    private Path file;

    private PathResolver resolver;

    private RootCAService service;

    @Before
    public void setUp() throws IOException {
        file = createTempFile("platformRootCA", ".pem");
        resolver = args -> file;
        service = new FileRootCAService(resolver, file.getFileName().toString());
    }

    @After
    public void tearDown() throws IOException {
        deleteIfExists(file);
    }

    @Test
    public void testSaveLoad()
            throws GeneralCryptoLibException, IOException, CertificateManagementException {
        AsymmetricServiceAPI asymmetricService = new AsymmetricService();
        KeyPair pair = asymmetricService.getKeyPairForSigning();
        CertificatesServiceAPI certificateService =
            new CertificatesService();
        RootCertificateData data = new RootCertificateData();
        X509DistinguishedName name =
            new X509DistinguishedName.Builder("TEST", "ES").build();
        data.setSubjectPublicKey(pair.getPublic());
        data.setSubjectDn(name);
        Date from = new Date();
        Date to = new Date(from.getTime() + 1000);
        ValidityDates dates = new ValidityDates(from, to);
        data.setValidityDates(dates);
        CryptoAPIX509Certificate certificate = certificateService
            .createRootAuthorityX509Certificate(data, pair.getPrivate());

        X509Certificate expected = certificate.getCertificate();
        service.save(expected);
        X509Certificate actual = service.load();
        assertEquals(expected, actual);
    }
}
