/*
 * 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.config.spring.batch.writers;


import java.nio.file.Path;

import org.apache.commons.codec.binary.Base64;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.transform.LineAggregator;
import org.springframework.core.io.FileSystemResource;

import com.scytl.products.ov.config.model.authentication.ExtendedAuthInformation;
import com.scytl.products.ov.constants.Constants;
import com.scytl.products.ov.sdm.config.spring.batch.GeneratedVotingCardOutput;


public class ExtendedAuthenticationWriter extends FlatFileItemWriter<GeneratedVotingCardOutput> {

    public ExtendedAuthenticationWriter(final Path path) {

        setLineAggregator(lineAggregator());
        setTransactional(false);
        setAppendAllowed(false);
        setShouldDeleteIfExists(true);
        setResource(new FileSystemResource(path.toString()));
    }

    private LineAggregator<GeneratedVotingCardOutput> lineAggregator() {
        return item -> {
            final String electionEventId = item.getElectionEventId();
            final ExtendedAuthInformation extendedAuthInformation = item.getExtendedAuthInformation();
            final String credentialId = item.getCredentialId();

            final String authId = extendedAuthInformation.getAuthenticationId().getDerivedKeyInEx();
            // get encoded or empty if not present
            final String extraParam = extendedAuthInformation.getExtendedAuthChallenge()
                .map(extendedAuthChallenge -> Base64
                    .encodeBase64String(extendedAuthChallenge.getDerivedChallenges().getDerivedKey().getEncoded()))
                .orElse(Constants.EMPTY);

            // get salt or empty if not present
            String salt = extendedAuthInformation.getExtendedAuthChallenge()
                .map(extendedAuthChallenge -> Base64.encodeBase64String(extendedAuthChallenge.getSalt()))
                .orElse(Constants.EMPTY);
            final String encryptedSVK = extendedAuthInformation.getEncryptedSVK();
            return String.format("%s,%s,%s,%s,%s,%s", authId, extraParam, encryptedSVK, electionEventId, salt,
                credentialId);
        };
    }
}
