/*
 * 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.sdm.domain.service.impl;

import com.scytl.products.ov.sdm.commons.domain.CreateVerificationCardIdsInput;
import com.scytl.products.ov.sdm.domain.service.VerificationCardDataGeneratorService;
import com.scytl.products.ov.sdm.domain.service.exception.VerificationCardDataGeneratorServiceException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Service
public class VerificationCardDataGeneratorServiceImpl implements VerificationCardDataGeneratorService {

    @Autowired
    private RestTemplate restClient;

    @Value("${CONFIG_GENERATOR_URL}")
    private String configServiceBaseUrl;

    private static final Logger LOGGER = LoggerFactory.getLogger(VerificationCardDataGeneratorServiceImpl.class);

    private static final String PRECOMPUTE_URL_PATH = "/precompute";

    @Override
    public BufferedReader precompute(String electionEventId, String verificationCardSetId, int numberOfVotingCards)
            throws IOException {

        CreateVerificationCardIdsInput createVerificationCardIdsInput = new CreateVerificationCardIdsInput();
        createVerificationCardIdsInput.setVerificationCardSetId(verificationCardSetId);
        createVerificationCardIdsInput.setNumberOfVerificationCardIds(numberOfVotingCards);
        createVerificationCardIdsInput.setElectionEventId(electionEventId);

        final String targetUrl = configServiceBaseUrl + PRECOMPUTE_URL_PATH;

        try {
            LOGGER.info("Starting pre-computation of verification card set {}...", verificationCardSetId);

            ResponseEntity<Resource> response =
                restClient.postForEntity(targetUrl, createVerificationCardIdsInput, Resource.class);

            return new BufferedReader(new InputStreamReader(response.getBody().getInputStream()));
        } catch (RestClientException e) {
            LOGGER.error("Error performing precompute request to endpoint '{}' : '{}'", targetUrl, e);
            throw new VerificationCardDataGeneratorServiceException(e);
        }
    }
}
