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

import javax.ejb.EJB;

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

import com.scytl.products.ov.commons.beans.VoteVerificationContextData;
import com.scytl.products.ov.commons.beans.exceptions.ResourceNotFoundException;
import com.scytl.products.ov.commons.crypto.KeystoreForObjectRepository;
import com.scytl.products.ov.commons.ui.ws.rs.ObjectMappers;

/**
 *
 */
public class CodesSecretKeystoreRepository implements KeystoreForObjectRepository {

    // The verification content repository.
    @EJB
    private VerificationContentRepository verificationContentRepository;

    /**
     * Find a keystore data string given this tenant identifier, the
     * electionEventIdentifier and the verification card set id. *
     * 
     * @param tenantId
     *            the tenant identifier.
     * @param electionEventId
     *            the election event identifier.
     * @param verificationCardSetId
     *            the verification card set 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 verificationCardSetId)
            throws ResourceNotFoundException {

        // recover from db
        VerificationContentEntity verificationContent = verificationContentRepository
            .findByTenantIdElectionEventIdVerificationCardSetId(tenantId, electionEventId, verificationCardSetId);

        VoteVerificationContextData voteVerificationContextData;
        try {
            voteVerificationContextData =
                ObjectMappers.fromJson(verificationContent.getJson(), VoteVerificationContextData.class);
        } catch (IOException e) {
            throw new ResourceNotFoundException("Can not convert from json to context data", e);
        }

        return new String(Base64.decodeBase64(voteVerificationContextData.getCodesSecretKeyKeyStore()));
    }
}
