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

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

import com.scytl.products.ov.commons.beans.exceptions.ResourceNotFoundException;
import com.scytl.products.ov.commons.infrastructure.persistence.BaseRepositoryImpl;
import com.scytl.products.ov.vv.domain.model.content.ElectoralAuthorityEntity;
import com.scytl.products.ov.vv.domain.model.content.ElectoralAuthorityRepository;

/**
 * Implementation of the repository with JPA
 */
@Stateless(name = "vv-ElectoralAuthorityRepositoryImpl")
public class ElectoralAuthorityRepositoryImpl extends BaseRepositoryImpl<ElectoralAuthorityEntity, Integer> implements ElectoralAuthorityRepository {

	// The name of the parameter which identifies the tenantId
	private static final String PARAMETER_TENANT_ID = "tenantId";

	// The name of the parameter which identifies the electionEventId
	private static final String PARAMETER_ELECTION_EVENT_ID = "electionEventId";

	// The name of the parameter which identifies the electoralAuthorityId
	private static final String PARAMETER_ELECTORAL_AUTHORITY_ID = "electoralAuthorityId";

	/**
	 * Searches for an electoral authority associated with the given tenant, election event and electoral authority ids.
	 * This implementation uses database access by executing a SQL-query to select the data to be retrieved.
	 *
	 * @param tenantId - the identifier of the tenant.
	 * @param electionEventId - the identifier of the electionEvent.
	 * @param electoralAuthorityId - the identifier of the electoralAuthority.
	 * @return a entity representing the electoral authority.
	 */
	@Override
	public ElectoralAuthorityEntity findByTenantIdElectionEventIdElectoralAuthorityId(String tenantId,
			String electionEventId, String electoralAuthorityId) throws ResourceNotFoundException {
		TypedQuery<ElectoralAuthorityEntity> query =
			entityManager
				.createQuery(
					"SELECT a FROM ElectoralAuthorityEntity a WHERE a.tenantId = :tenantId AND a.electionEventId = :electionEventId AND a.electoralAuthorityId = :electoralAuthorityId",
					ElectoralAuthorityEntity.class);
		query.setParameter(PARAMETER_TENANT_ID, tenantId);
		query.setParameter(PARAMETER_ELECTION_EVENT_ID, electionEventId);
		query.setParameter(PARAMETER_ELECTORAL_AUTHORITY_ID, electoralAuthorityId);

		try {
            return query.getSingleResult();
        } catch (NoResultException e) {
			throw new ResourceNotFoundException("", e);
		}
	}
}
