/*
 * 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.model.authentication;

import javax.ejb.EJB;
import javax.json.JsonObject;

import org.apache.commons.codec.binary.Base64;

import com.scytl.products.ov.commons.beans.exceptions.ResourceNotFoundException;
import com.scytl.products.ov.commons.crypto.KeystoreForObjectRepository;
import com.scytl.products.ov.commons.util.JsonUtils;

/**
 * 
 */
public class AuthenticationKeyStoreForObjectRepository implements KeystoreForObjectRepository {

	// The encryption keystore name in the contents json.
	private static final String ENCRYPTION_KEYSTORE = "authenticationTokenSignerKeystore";

	// The verification content repository.
	@EJB
	AuthenticationContentRepository repository;

	/**
	 * Find a keystore data string given this tenant identifier, the electionEventIdentifier
	 *
	 * @param tenantId the tenant identifier.
	 * @param electionEventId the election event identifier.
	 * @param objectId - It doee not apply.
	 * @return the keystore data represented as a string.
	 * @throws ResourceNotFoundException if the keystore data can not be found.
	 * @see com.scytl.products.ov.commons.crypto.KeystoreForObjectRepository#getJsonByTenantEEIDObjectId(java.lang.String,
	 *      java.lang.String, java.lang.String)
	 */
	@Override
	public String getJsonByTenantEEIDObjectId(String tenantId, String electionEventId, String objectId)
			throws ResourceNotFoundException {

		// recover from db
		AuthenticationContentEntity authenticationContent =
			repository.findByTenantIdElectionEventId(tenantId, electionEventId);

		// convert to json object
		JsonObject object = JsonUtils.getJsonObject(authenticationContent.getJson());

		return new String(Base64.decodeBase64(object.getString(ENCRYPTION_KEYSTORE)));

	}
}
