/*
 * 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.application.service;

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.ov.sdm.application.log.SdmSecureLogEvent;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.DirectoryStream;
import java.nio.file.Path;

import com.scytl.products.ov.sdm.domain.model.votingcardset.VotingCardSetUploadRepository;
import com.scytl.products.ov.sdm.domain.service.ConfigConstants;
import static java.nio.file.Files.newDirectoryStream;

/**
 * Uploads the signed extendedAuthentication information
 */
@Service
public class ExtendedAuthenticationUploadService {

    @Autowired
    SignatureService signatureService;

    @Autowired
    VotingCardSetUploadRepository votingCardSetUploadRepository;

    @Autowired
    SecureLoggingWriter secureLogger;

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

    /**
     * Uploads the extended authentication information belonging to a voting
     * card set
     * 
     * @param extAuthPath
     * @param electionEventId
     * @param adminBoardId
     * @throws IOException
     */
    public void uploadExtendedAuthenticationFiles(final Path extAuthPath, final String electionEventId,
            final String adminBoardId) throws IOException {

        try (DirectoryStream<Path> files = newDirectoryStream(extAuthPath, ConfigConstants.CSV_GLOB)) {
            for (Path file : files) {
                String name = file.getFileName().toString();
                if (name.startsWith(ConfigConstants.CONFIG_FILE_EXTENDED_AUTHENTICATION_DATA)) {
                    LOGGER.info("Uploading extended authentication file and its signature" + name);
                    uploadExtendedAuthentication(electionEventId, adminBoardId, file);
                }
            }
        }
    }

    private void uploadExtendedAuthentication(final String electionEventId, final String adminBoardId,
            final Path filePath) throws IOException {

        String fileName = filePath.getFileName().toString();

        try (InputStream stream = signatureService.newCSVAndSignatureInputStream(filePath)) {
            votingCardSetUploadRepository.uploadExtendedAuthData(electionEventId, adminBoardId, stream);

            Path signatureFile = filePath.resolveSibling(filePath.getFileName() + ConfigConstants.SIGN);
            byte[] signature = Files.readAllBytes(signatureFile);
            String b64FileSignature = new String(signature, StandardCharsets.UTF_8);

            secureLogger.log(Level.INFO,
                new LogContent.LogContentBuilder()
                    .logEvent(SdmSecureLogEvent.EXTENDED_AUTHENTICATION_UPLOADED_SUCCESSFULLY)
                    .additionalInfo("file_name", filePath.getFileName().toString())
                    .additionalInfo("file_s", b64FileSignature).createLogInfo());

        } catch (IOException e) {
        	LOGGER.error("Error trying to upload Extended Authentication.", e);
            secureLogger.log(Level.ERROR,
                new LogContent.LogContentBuilder().electionEvent(electionEventId)
                    .logEvent(SdmSecureLogEvent.EXTENDED_AUTHENTICATION_UPLOADING_FAILED)
                    .additionalInfo("file_name", fileName)
                    .additionalInfo("err_desc", "Error uploading extended authentication file and its signature")
                    .createLogInfo());
        }

    }
}
