/*
 * 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 java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.PrivateKey;
import java.util.function.Supplier;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.products.ov.commons.path.PathResolver;
import com.scytl.products.ov.sdm.domain.service.ConfigConstants;

@Service
public class ExtendedAuthenticationService {

    @Autowired
    private PathResolver pathResolver;

    @Autowired
    private SignatureService signatureService;

    /**
     * The Constant LOGGER.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ExtendedAuthenticationService.class);

    /**
     * Signs the extended authentication files
     * 
     * @param electionEventId
     * @param votingCardSetId
     * @param privateKey
     * @return
     * @throws IOException
     */
    public boolean signExtendedAuthentication(final String electionEventId, final String votingCardSetId,
            final PrivateKey privateKey) throws IOException {

        Path extendAuthPath = pathResolver.resolve(ConfigConstants.CONFIG_FILES_BASE_DIR).resolve(electionEventId)
            .resolve(ConfigConstants.CONFIG_DIR_NAME_ONLINE)
            .resolve(ConfigConstants.CONFIG_FILE_EXTENDED_AUTHENTICATION_DATA).resolve(votingCardSetId);

        boolean result = evaluateSignatureProccess(() -> {
            long numberFailed = 0;
            try {
                numberFailed = Files.walk(extendAuthPath, 1).filter(csvPath -> {
                    Boolean failed = Boolean.FALSE;
                    try {
                        String name = csvPath.getFileName().toString();
                        if (name.startsWith(ConfigConstants.CONFIG_FILE_EXTENDED_AUTHENTICATION_DATA)
                            && name.endsWith(ConfigConstants.CSV)) {

                            LOGGER.info("Signing file " + name);
                            String signatureB64 = signatureService.signCSV(privateKey, csvPath.toFile());
                            LOGGER.info("Saving signature");
                            signatureService.saveCSVSignature(signatureB64, csvPath);
                        }
                    } catch (IOException | GeneralCryptoLibException e) {
                    	LOGGER.info("File signing failed.", e);
                    	failed = true;
                    }
                    return failed;
                }).count();
            } catch (IOException e) {
            	LOGGER.info("File signing failed.", e);
                return Boolean.FALSE;
            }
            return numberFailed == 0;
        });

        if (!result) {
            signatureService.deleteSignaturesFromCSVs(extendAuthPath);
        }
        return result;
    }

    private boolean evaluateSignatureProccess(final Supplier<Boolean> arg) {
        return arg.get();
    }



}
