/*
 * 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 java.io.IOException;

import com.scytl.products.ov.sdm.application.log.SdmSecureLogEvent;
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.http.HttpStatus;
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;

import com.scytl.products.ov.sdm.domain.model.preconfiguration.PreconfigurationRepository;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * The election event end-point.
 */
@RestController
@RequestMapping("/sdm-ws-rest/preconfiguration")
@Api(value = "Pre-configuration REST API", description = "")
public class PreconfigurationResource {

    // The election event repository
    @Autowired
    private PreconfigurationRepository preconfigurationRepository;

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

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

    @Autowired
    private TransactionInfoProvider transactionInfoProvider;

    // The configuration of contests / elections
    @Value("${elections.config.filename}")
    private String configFile;

    @Value("${adminPortal.enabled}")
    private boolean isAdminPortalEnabled;

    @Autowired
    private SecureLoggingWriter secureLogger;

    @RequestMapping(method = RequestMethod.POST, produces = "application/json")
    @ResponseStatus(value = HttpStatus.CREATED)
    @ApiOperation(value = "Get configuration", notes = "Service to retrieve the configuration of administration"
        + " boards and election events.", response = String.class)
    public String createElectionEvent() throws IOException {

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

        secureLogger.log(Level.INFO, new LogContent.LogContentBuilder()
                .logEvent(SdmSecureLogEvent.SDM_SYNCHRONIZING_WITH_AP)
                .createLogInfo());

        String result = null;
        if (!isAdminPortalEnabled) {

            LOGGER.info(
                    "The application is configured to not have connectivity to Admin Portal, " +
                            "check if this is the expected behavior");

            secureLogger.log(Level.ERROR,
                    new LogContent.LogContentBuilder()
                            .logEvent(SdmSecureLogEvent.SDM_SYNCHRONIZATION_WITH_AP_FAILED)
                            .additionalInfo("err_desc",
                                    "The application is configured to not have connectivity to Admin Portal, " +
                                    "check if this is the expected behavior")
                            .createLogInfo());
        }
        // call to end point to download data from administration portal
        else if (preconfigurationRepository.download(configFile)) {
            // process the download data
            result = preconfigurationRepository.readFromFileAndSave(configFile);
        }

        secureLogger.log(Level.INFO, new LogContent.LogContentBuilder()
                .logEvent(SdmSecureLogEvent.SDM_SYNCHRONIZED_WITH_AP_SUCCESSFULLY)
                .createLogInfo());

        return result;
    }
}
