/*
 * 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.choicecodes.domain.services;

import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.scytl.products.ov.channel.cc.orchestrator.choicecodes.domain.model.computedvalues.ComputedValues;
import com.scytl.products.ov.channel.cc.orchestrator.choicecodes.domain.model.computedvalues.ComputedValuesRepository;
import com.scytl.products.ov.commons.beans.exceptions.DuplicateEntryException;
import com.scytl.products.ov.commons.beans.exceptions.EntryPersistenceException;
import com.scytl.products.ov.commons.beans.exceptions.ResourceNotFoundException;
import com.scytl.products.ov.commons.dto.ChoiceCodeGenerationDTO;
import com.scytl.products.ov.commons.dto.ChoiceCodeGenerationResPayload;
import com.scytl.products.ov.commons.ui.ws.rs.ObjectMappers;

/**
 * Service for handling computed values.
 */
@Stateless
public class ComputedValuesService {

    @Inject
    private ComputedValuesRepository computedValuesRepository;

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void create(String tenantId, String electionEventId, String verificationCardSetId, int chunkId)
            throws DuplicateEntryException {

        ComputedValues computedValues = new ComputedValues();
        computedValues.setTenantId(tenantId);
        computedValues.setElectionEventId(electionEventId);
        computedValues.setVerificationCardSetId(verificationCardSetId);
        computedValues.setChunkId(chunkId);
        computedValuesRepository.save(computedValues);

    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void update(String tenantId, String electionEventId, String verificationCardSetId,
            int chunkId, List<ChoiceCodeGenerationDTO<ChoiceCodeGenerationResPayload>> computationResults)
            throws EntryPersistenceException, ResourceNotFoundException {

        String json;
        try {
            json = ObjectMappers.toJson(computationResults);
        } catch (JsonProcessingException e) {
            throw new IllegalStateException("Failed to deserialize to json", e);
        }

        ComputedValues computedValues = computedValuesRepository
            .findByTenantIdElectionEventIdVerificationCardSetId(tenantId, electionEventId, verificationCardSetId, chunkId);
        computedValues.setJson(json);
        computedValuesRepository.update(computedValues);
    }

}
