/*
 * 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.au.services.domain.utils;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.certificates.bean.X509DistinguishedName;
import com.scytl.cryptolib.certificates.factory.CryptoX509Certificate;
import com.scytl.products.ov.au.services.domain.model.authentication.AuthenticationContentEntity;
import com.scytl.products.ov.commons.util.JsonUtils;
import com.scytl.products.ov.commons.util.ResourceStreamUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

public class AuthenticationUtils {

    public static final String ELECTION_EVENT_ID = "100";

    public static final String TENANT_ID = "100";

    private static final String CREDENTIALS_CA = "credentialsCA";

    private static final String ELECTION_ROOT_CA = "electionRootCA";

    // Create a credential factory to convert string to X509 certificate
    private static final CertificateFactory cf;

    static {

        try {
            cf = CertificateFactory.getInstance("X.509");
        } catch (CertificateException e) {
            throw new RuntimeException("Unable to create certificate factory instance");
        }
    }

    public static AuthenticationContentEntity generateAuthenticationContentEntity() {

        AuthenticationContentEntity entity = new AuthenticationContentEntity();
        entity.setElectionEventId(ELECTION_EVENT_ID);
        entity.setTenantId(TENANT_ID);
        final String json = ResourceStreamUtils.readResourceStream("authenticationContent.json");
        entity.setJson(json);
        return entity;

    }

    public static X509Certificate getX509Cert(String certificateString) throws CertificateException {
        InputStream inputStream = new ByteArrayInputStream(certificateString.getBytes(StandardCharsets.UTF_8));
        return (X509Certificate) cf.generateCertificate(inputStream);
    }

    public static X509DistinguishedName getDistinguishName(X509Certificate x509Cert) throws GeneralCryptoLibException {
        CryptoX509Certificate wrappedCertificate = new CryptoX509Certificate(x509Cert);
        return wrappedCertificate.getSubjectDn();
    }

    public static String getCredentialCA(String authCertsJson) {
        // Intermediate certificate -> Credentials CA
        return JsonUtils.getJsonObject(authCertsJson).getString(CREDENTIALS_CA);

    }

    public static String getRootCA(String authCertsJson) {
        // Intermediate certificate -> Credentials CA
        return JsonUtils.getJsonObject(authCertsJson).getString(ELECTION_ROOT_CA);

    }

}
