/*
 * 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.vv.domain.model.content;

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

import javax.inject.Inject;
import javax.json.JsonObject;

import com.scytl.products.ov.commons.beans.exceptions.ResourceNotFoundException;
import com.scytl.products.ov.commons.beans.validation.CryptographicOperationException;
import com.scytl.products.ov.commons.util.JsonUtils;
import com.scytl.products.ov.vv.domain.model.verificationset.VerificationSetEntity;
import com.scytl.products.ov.vv.domain.model.verificationset.VerificationSetRepository;

/**
 * Repository for handling Private Keys entities for specific object like ballot box.
 */
public class CastCodeSignerCertRepository {

	private static final String CERTIFICATE = "voteCastCodeSignerCert";

	@Inject
	private VerificationSetRepository verificationSetRepository;

	@Inject
	private CertificateFactory certificateFactory;

	/**
	 * Searches for an private key with the given tenant, election event, object identifier and alias.
	 *
	 * @param tenantId - the identifier of the tenant.
	 * @param eeid - the identifier of the electionEvent.
	 * @param objectId - the identifier of the object.
	 * @param alias - the private key alias.
	 * @param verificationCardSetId - the verification card set id
	 * @return a entity representing the private key.
	 * @throws CryptographicOperationException if there is an error recovering the private key.
	 * @throws ResourceNotFoundException if the keystore containing the private key can not be found.
	 */
	public X509Certificate findByTenantEEIDVerificationCardSetId(String tenantId, String eeid, String verificationCardSetId)
			throws CryptographicOperationException, ResourceNotFoundException {

		VerificationSetEntity verificationSet = verificationSetRepository
			.findByTenantIdElectionEventIdVerificationCardSetId(tenantId, eeid, verificationCardSetId);
		JsonObject object = JsonUtils.getJsonObject(verificationSet.getJSON());
		String castCodeSignerCertString = object.getString(CERTIFICATE);
		byte[] castCodeSignerCertBytes = castCodeSignerCertString.getBytes(StandardCharsets.UTF_8);

		try (InputStream is = new ByteArrayInputStream(castCodeSignerCertBytes)) {
			return (X509Certificate) certificateFactory.generateCertificate(is);

		} catch (CertificateException | IOException e) {
			throw new CryptographicOperationException("Can not recover cast code signing certificate from the contents: ",
				e);
		}

	}
}
