/*
 * 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.ei.services.domain.model.ballotbox;

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

import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * Ballot box keystore respository implementation.
 */
public class BallotBoxKeystoreRepository implements KeystoreForObjectRepository {

	private static final Logger LOG = LoggerFactory.getLogger("std");

	private static final I18nLoggerMessages I18N = I18nLoggerMessages.getInstance();

	// The Constant KEYSTORE.
	private static final String KEYSTORE = "keystore";

	// The ballot box content repository.
	@EJB
	private BallotBoxContentRepository ballotBoxContentRepository;

	/**
	 * Find a keystore data string given this tenant identifier and the electionEventIdentifier. *
	 * 
	 * @param tenantId the tenant identifier.
	 * @param electionEventId the election event identifier.
	 * @param ballotBoxId the ballot box identifier.
	 * @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 ballotBoxId)
			throws ResourceNotFoundException {

		LOG.info(I18N.getMessage("BallotBoxContentService.getBallotBoxContent.recoveringBallotBoxContent"), tenantId,
			electionEventId, ballotBoxId);

		// recover from db
		BallotBoxContent ballotBoxContent =
			ballotBoxContentRepository.findByTenantIdElectionEventIdBallotBoxId(tenantId, electionEventId, ballotBoxId);

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

		LOG.info(I18N.getMessage("BallotBoxContentService.getBallotBoxContent.ballotBoxContentFound"), tenantId,
			electionEventId, ballotBoxId);

		return new String(Base64.decode(object.getString(KEYSTORE)));
	}
}
