/*
 * 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 org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.transform.LineAggregator;
import org.springframework.core.io.FileSystemResource;

import java.nio.file.Path;

import com.scytl.products.ov.sdm.config.spring.batch.GeneratedVotingCardOutput;

public class VoterInformationWriter extends FlatFileItemWriter<GeneratedVotingCardOutput> {

    public VoterInformationWriter(final Path path) {

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

    private LineAggregator<GeneratedVotingCardOutput> lineAggregator() {
        return item -> {
            final String votingCardId = item.getVotingCardId();
            final String ballotId = item.getBallotId();
            final String ballotBoxId = item.getBallotBoxId();
            final String credentialId = item.getCredentialId();
            final String electionEventId = item.getElectionEventId();
            final String votingCardSetId = item.getVotingCardSetId();
            final String verificationCardId = item.getVerificationCardId();
            final String verificationCardSetId = item.getVerificationCardSetId();

            return String.format("%s,%s,%s,%s,%s,%s,%s,%s", votingCardId, ballotId, ballotBoxId, credentialId,
                electionEventId, votingCardSetId, verificationCardId, verificationCardSetId);
        };
    }
}
