/*
 * 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.cr.services.infrastructure.persistence.platform;

import javax.ejb.Stateless;
import javax.persistence.TypedQuery;

import com.scytl.products.ov.commons.infrastructure.persistence.BaseRepositoryImpl;
import com.scytl.products.ov.commons.logging.domain.model.LoggingKeystoreEntity;
import com.scytl.products.ov.commons.logging.domain.model.LoggingKeystoreRepository;
import com.scytl.products.ov.cr.services.domain.model.platform.CrLoggingKeystoreEntity;
import com.scytl.products.ov.cr.services.domain.model.platform.CrLoggingKeystoreRepository;

/**
 * Implementation of the repository with JPA
 */
@Stateless
@CrLoggingKeystoreRepository
public class CrLogginKeystoreRepositoryImpl extends BaseRepositoryImpl<LoggingKeystoreEntity, Long>
        implements LoggingKeystoreRepository {

    private static final String PARAMETER_KEY_TYPE = "keyType";

    private static final int INDEX_OF_RESULT_ROW_TO_USE = 0;

    /**
     * @see com.scytl.products.ov.commons.logging.domain.model.LoggingKeystoreRepository#checkIfKeystoreExists(java.lang.String)
     */
    @Override
    public boolean checkIfKeystoreExists(final String keyType) {

        TypedQuery<CrLoggingKeystoreEntity> query = entityManager.createQuery(
            "SELECT a FROM CrLoggingKeystoreEntity a where a.keyType=:keyType", CrLoggingKeystoreEntity.class);
        query.setParameter(PARAMETER_KEY_TYPE, keyType);
        
        return query.getResultList().size() == 1;
    }

    /**
     * @see com.scytl.products.ov.commons.logging.domain.model.LoggingKeystoreRepository#getLoggingKeystoreByType(java.lang.String)
     */
    @Override
    public LoggingKeystoreEntity getLoggingKeystoreByType(final String keyType) {

        TypedQuery<CrLoggingKeystoreEntity> query = entityManager.createQuery(
            "SELECT a FROM CrLoggingKeystoreEntity a where a.keyType=:keyType", CrLoggingKeystoreEntity.class);
        query.setParameter(PARAMETER_KEY_TYPE, keyType);

        return query.getResultList().get(INDEX_OF_RESULT_ROW_TO_USE);
    }
}
