/*
 * 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.ui.ws.rs.application;

import com.scytl.products.oscore.logging.api.domain.Level;
import com.scytl.products.oscore.logging.api.domain.LogContent;
import com.scytl.products.oscore.logging.api.writer.SecureLoggingWriter;
import com.scytl.products.oscore.logging.core.provider.TransactionInfoProvider;
import com.scytl.products.ov.commons.infrastructure.remote.client.RetrofitException;
import com.scytl.products.ov.sdm.application.log.SdmSecureLogEvent;
import com.scytl.products.ov.sdm.application.service.ChoiceCodesComputationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

/**
 * Controller for checking the status of the choice codes computation.
 */
@RestController
@RequestMapping("/sdm-ws-rest/choicecodes")
@Api(value = "Computed values REST API")
public class ChoiceCodesComputationResource {

    @Autowired
    private TransactionInfoProvider transactionInfoProvider;

    @Autowired
    SecureLoggingWriter secureLogger;

    @Autowired
    ChoiceCodesComputationService choiceCodesComputationService;

    @Value("${tenantID}")
    private String tenantId;

    /**
     * Check if computed choice codes are ready.
     *
     * @throws IOException
     *             if something fails uploading voting card sets or electoral
     *             authorities.
     */
    @RequestMapping(value = "/electionevent/{electionEventId}/status", method = RequestMethod.POST, produces = "application/json")
    @ResponseStatus(value = HttpStatus.OK)
    @ApiOperation(value = "Check if computed choice codes are ready and update its status", notes = "Service to check the status of computed choice codes.")
    public void updateChoiceCodesComputationStatus(
            final @ApiParam(value = "String", required = true) @PathVariable String electionEventId)
            throws IOException, RetrofitException {

        transactionInfoProvider.generate(tenantId, "", "");

        secureLogger.log(Level.INFO, new LogContent.LogContentBuilder()
            .logEvent(SdmSecureLogEvent.CHECKING_COMPUTED_VALUES).electionEvent(electionEventId).createLogInfo());

        choiceCodesComputationService.updateChoiceCodesComputationStatus(electionEventId);
    }
}
