/*
 * 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.ei.services.domain.service.ballotbox;

import javax.inject.Inject;
import javax.json.JsonObject;

import com.scytl.products.ov.commons.beans.exceptions.EntryPersistenceException;
import com.scytl.products.ov.commons.beans.exceptions.ResourceNotFoundException;
import com.scytl.products.ov.commons.util.JsonUtils;
import com.scytl.products.ov.ei.services.domain.model.ballotbox.BallotBoxInformation;
import com.scytl.products.ov.ei.services.domain.model.ballotbox.BallotBoxInformationRepository;
import com.scytl.products.ov.ei.services.domain.model.ballotbox.BallotBoxStatus;

/**
 * Service for managing ballot box information.
 */
public class BallotBoxInformationService {

    /**
     * 
     */
    private static final String JSON_PARAMETER_TEST = "test";



    @Inject
    private BallotBoxInformationRepository ballotBoxInformationRepository;

    /**
     * Returns true if the ballot box is for testing purposes.
     * 
     * @param tenantId
     *            the tenant id.
     * @param electionEventId
     *            the election event id.
     * @param ballotBoxId
     *            the ballot box id.
     * @return True if the ballot box is for testing. Otherwise, false.
     * @throws ResourceNotFoundException
     */
    public boolean isBallotBoxForTest(String tenantId, String electionEventId, String ballotBoxId)
            throws ResourceNotFoundException {
        BallotBoxInformation ballotBoxInformation = ballotBoxInformationRepository
            .findByTenantIdElectionEventIdBallotBoxId(tenantId, electionEventId, ballotBoxId);
        JsonObject ballotBoxInformationJson = JsonUtils.getJsonObject(ballotBoxInformation.getJson());

        return ballotBoxInformationJson.getBoolean(JSON_PARAMETER_TEST);
    }

    /**
     * Blocks the ballot box that matches with the given ids true if the ballot box is for testing purposes.
     *
     * @param tenantId
     *            the tenant id.
     * @param electionEventId
     *            the election event id.
     * @param ballotBoxId
     *            the ballot box id.
     * @param newStatus
     * @throws ResourceNotFoundException
     *             if the ballot box does not exist
     */
    public BallotBoxInformation changeBallotBoxStatus(String tenantId, String electionEventId, String ballotBoxId,
                                                      BallotBoxStatus newStatus) throws ResourceNotFoundException, EntryPersistenceException {

        BallotBoxInformation ballotBoxInformation = ballotBoxInformationRepository
            .findByTenantIdElectionEventIdBallotBoxId(tenantId, electionEventId, ballotBoxId);
        ballotBoxInformation.setStatus(newStatus);
        return ballotBoxInformationRepository.update(ballotBoxInformation);

    }

}
