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

import com.scytl.products.ov.channel.cc.orchestrator.mixdec.domain.model.MixDecBallotBox;
import com.scytl.products.ov.commons.beans.exceptions.DuplicateEntryException;
import com.scytl.products.ov.commons.infrastructure.persistence.BaseRepositoryImpl;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.TypedQuery;

/**
 * Implementation of VoteRepository.
 */
@Stateless
public class MixDecBallotBoxRepositoryImpl extends BaseRepositoryImpl<MixDecBallotBox, Integer>
        implements MixDecBallotBoxRepository {

    private static final String PARAMETER_TENANT_ID = "tenantId";

    private static final String PARAMETER_ELECTION_EVENT_ID = "electionEventId";

    private static final String PARAMETER_BALLOT_BOX_ID = "ballotBoxId";

    @Override
    public List<MixDecBallotBox> findByTenantIdElectionEventIdBallotBoxId(final String tenantId,
            final String electionEventId, final String ballotBoxId) {
        final TypedQuery<MixDecBallotBox> query = entityManager.createQuery(
            "SELECT b FROM MixDecBallotBox b WHERE b.tenantId = :tenantId AND b.electionEventId = :electionEventId AND b.ballotBoxId = :ballotBoxId",
            MixDecBallotBox.class);
        query.setParameter(PARAMETER_TENANT_ID, tenantId);
        query.setParameter(PARAMETER_ELECTION_EVENT_ID, electionEventId);
        query.setParameter(PARAMETER_BALLOT_BOX_ID, ballotBoxId);
        return query.getResultList();
    }

    @Override
    public void save(String tenantId, String electionEventId, String ballotBoxId, String encryptedVote)
            throws DuplicateEntryException {

        MixDecBallotBox mixDecBallotBox = new MixDecBallotBox();

        mixDecBallotBox.setTenantId(tenantId);
        mixDecBallotBox.setElectionEventId(electionEventId);
        mixDecBallotBox.setBallotBoxId(ballotBoxId);
        mixDecBallotBox.setVote(encryptedVote);

        save(mixDecBallotBox);
    }

    @Override
    public List<MixDecBallotBox> findByTenantIdElectionEventIdBallotBoxId(String tenantId, String electionEventId,
            String ballotBoxId, int start, int size) {
        final TypedQuery<MixDecBallotBox> query = entityManager.createQuery(
            "SELECT b FROM MixDecBallotBox b WHERE b.tenantId = :tenantId AND b.electionEventId = :electionEventId AND b.ballotBoxId = :ballotBoxId",
            MixDecBallotBox.class);
        query.setParameter(PARAMETER_TENANT_ID, tenantId);
        query.setParameter(PARAMETER_ELECTION_EVENT_ID, electionEventId);
        query.setParameter(PARAMETER_BALLOT_BOX_ID, ballotBoxId);
        query.setFirstResult(start);
        query.setMaxResults(size);
        return query.getResultList();
    }

}
