/*
 * 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.vm.infrastructure.persistence;

import static org.junit.Assert.*;

import javax.inject.Inject;
import javax.persistence.EntityManager;

import org.junit.Rule;
import org.junit.Test;

import com.scytl.products.ov.commons.logging.domain.model.LoggingKeystoreEntity;
import com.scytl.products.ov.vm.domain.model.platform.VmLoggingKeystoreEntity;

import de.akquinet.jbosscc.needle.annotation.ObjectUnderTest;
import de.akquinet.jbosscc.needle.db.transaction.TransactionHelper;
import de.akquinet.jbosscc.needle.db.transaction.VoidRunnable;
import de.akquinet.jbosscc.needle.junit.DatabaseRule;
import de.akquinet.jbosscc.needle.junit.NeedleRule;

public class VmLoggingKeystoreRepositoryImplTest {
	
	private final String keyType = "keyType";
	
	@Rule
	public DatabaseRule databaseRule = new DatabaseRule();
	
	@Inject
	private EntityManager entityManager;
	
	@Rule
	public NeedleRule needleRule = new NeedleRule(databaseRule);
	
	private TransactionHelper transactionHelper = databaseRule.getTransactionHelper();
	
	@ObjectUnderTest
	VmLoggingKeystoreRepositoryImpl rut;

	private boolean existsResult;
	private LoggingKeystoreEntity entityResult;

	@Test
	public void testCheckIfKeystoreExistsSuccessful() throws Exception {
		buildTestData();
		
		transactionHelper.executeInTransaction(new VoidRunnable() {
			@Override
			public void doRun(EntityManager entityManager) throws Exception {
				existsResult = rut.checkIfKeystoreExists(keyType);
			}
		});
		
		assertTrue(existsResult);
	}
	
	@Test
	public void testGetLoggingKeystoreByTypeSuccesful() throws Exception
	{
		buildTestData();
		
		transactionHelper.executeInTransaction(new VoidRunnable() {
			@Override
			public void doRun(EntityManager entityManager) throws Exception {
				entityResult = rut.getLoggingKeystoreByType(keyType);
			}
		});
		
		assertEquals(keyType, entityResult.getKeyType());
	}

	private void buildTestData() {
		VmLoggingKeystoreTestdataBuilder dataBuilder = new VmLoggingKeystoreTestdataBuilder(entityManager);
		
		VmLoggingKeystoreEntity vmLoggingKeystoreEntity = new VmLoggingKeystoreEntity();
		vmLoggingKeystoreEntity.setKeyType(keyType);
		
		dataBuilder.setVmLoggingKeystoreEntity(vmLoggingKeystoreEntity);
		
		dataBuilder.buildAndSave();
	}
	
}
