/*
 * 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.commons.crypto;

import javax.crypto.SecretKey;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.scytl.keystore.cryptoapi.CryptoAPIScytlKeyStore;
import com.scytl.products.ov.commons.beans.exceptions.ResourceNotFoundException;
import com.scytl.products.ov.commons.beans.validation.CryptographicOperationException;

/**
 * Repository for handling Secret Key entities for specific object like ballot box.
 */
public class SecretKeyForObjectRepository {

	private final KeystoreForObjectOpener keystoreOpener;

	private final PasswordForObjectRepository passwordRepository;

	/**
	 * Constructor for a keystore based secret key repository.
	 * 
	 * @param keystoreOpener the keystore opener that will be used to locate and retrieve the keystore instance.
	 * @param passwordRepository the repository that will be used to retrieve the keystore key password.
	 */
	public SecretKeyForObjectRepository(KeystoreForObjectOpener keystoreOpener,
			PasswordForObjectRepository passwordRepository) {
		this.keystoreOpener = keystoreOpener;
		this.passwordRepository = passwordRepository;
	}

	/**
	 * Searches for a secret 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.
	 * @return a entity representing the secret key.
	 * @throws CryptographicOperationException if there is an error recovering the secret key.
	 * @throws ResourceNotFoundException if the keystore containing the secret key can not be found.
	 */
	public SecretKey findByTenantEEIDObjectIdAlias(String tenantId, String eeId, String objectId, String alias)
			throws CryptographicOperationException, ResourceNotFoundException {
		CryptoAPIScytlKeyStore keystore = keystoreOpener.openForTenantEEIDObjectIdAlias(tenantId, eeId, objectId, alias);
		String password = passwordRepository.getByTenantEEIDObjectIdAlias(tenantId, eeId, objectId, alias);

		try {
			return keystore.getSecretKeyEntry(alias, password.toCharArray());
		} catch (GeneralCryptoLibException e) {
			throw new CryptographicOperationException("Can not recover private key from keystore: ", e);
		}
	}

}
