/*
 * 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.channel.cc.orchestrator.infrastructure.persistence;

import com.scytl.products.ov.channel.cc.orchestrator.domain.platform.OrchestratorLoggingKeystoreEntity;
import javax.ejb.Stateless;
import javax.persistence.TypedQuery;

import com.scytl.products.ov.channel.cc.orchestrator.domain.platform.OrchestratorPlatformCARepository;
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;

/**
 * Implementation of the repository with JPA
 */
@Stateless
@OrchestratorPlatformCARepository
public class OrchestratorLoggingKeystoreRepositoryImpl 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 LoggingKeystoreRepository#checkIfKeystoreExists(String)
     */
    @Override
    public boolean checkIfKeystoreExists(final String keyType) {

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

        return query.getResultList().size() == 1;
    }

    /**
     * @see LoggingKeystoreRepository#getLoggingKeystoreByType(String)
     */
    @Override
    public LoggingKeystoreEntity getLoggingKeystoreByType(final String keyType) {

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

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

