/*
 * 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 javax.ejb.Stateless;
import javax.persistence.TypedQuery;

import com.scytl.products.ov.channel.cc.orchestrator.domain.model.tenant.OrTenantKeystoreEntity;
import com.scytl.products.ov.channel.cc.orchestrator.domain.model.tenant.OrTenantKeystoreRepository;
import com.scytl.products.ov.commons.domain.model.tenant.TenantKeystoreEntity;
import com.scytl.products.ov.commons.domain.model.tenant.TenantKeystoreRepository;
import com.scytl.products.ov.commons.infrastructure.persistence.BaseRepositoryImpl;

@Stateless
@OrTenantKeystoreRepository
public class OrTenantKeystoreRepositoryImpl extends BaseRepositoryImpl<TenantKeystoreEntity, Long>
        implements TenantKeystoreRepository {

    private static final String PARAMETER_KEY_TYPE = "keyType";

    private static final String PARAMETER_TENANT_ID = "tenantId";

    private static final int INDEX_OF_RESULT_ROW_TO_USE = 0;

    /**
     * @see TenantKeystoreRepository#getByTenantAndType(String,
     *      String)
     */
    @Override
    public TenantKeystoreEntity getByTenantAndType(final String tenantId, final String keyType) {

        TypedQuery<OrTenantKeystoreEntity> query = entityManager.createQuery(
                "SELECT a FROM OrTenantKeystoreEntity a where a.keyType=:keyType AND a.tenantId=:tenantId",
                OrTenantKeystoreEntity.class);

        query.setParameter(PARAMETER_KEY_TYPE, keyType);
        query.setParameter(PARAMETER_TENANT_ID, tenantId);

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

    /**
     * @see TenantKeystoreRepository#checkIfKeystoreExists(String,
     *      String)
     */
    @Override
    public boolean checkIfKeystoreExists(final String tenantId, final String keyType) {

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