/*
 * 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 com.fasterxml.jackson.core.JsonProcessingException;
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 java.nio.charset.StandardCharsets;
import java.nio.file.Path;

import com.scytl.products.ov.config.commands.voters.datapacks.beans.VerificationCardCodesDataPack;
import com.scytl.products.ov.config.exceptions.CreateVotingCardSetException;
import com.scytl.products.ov.sdm.config.spring.batch.GeneratedVotingCardOutput;
import com.scytl.products.ov.utils.ConfigObjectMapper;

public class CodesMappingTableWriter  extends FlatFileItemWriter<GeneratedVotingCardOutput> {

    private final static ConfigObjectMapper mapper = new ConfigObjectMapper();

    public CodesMappingTableWriter(final Path path) {

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

    private LineAggregator<GeneratedVotingCardOutput> lineAggregator() {

        return item -> {
            final VerificationCardCodesDataPack verificationCardCodesDataPack = item.getVerificationCardCodesDataPack();
            String mappingAsJSONB64;
            try {
                mappingAsJSONB64 = Base64.encodeBase64String(mapper.fromJavaToJSON(
                verificationCardCodesDataPack.getCodesMappingTable()).getBytes(StandardCharsets.UTF_8));
            } catch (JsonProcessingException e) {
                throw new CreateVotingCardSetException(
                    "Exception while trying to encode codes mapping table to Json", e);
            }
            final String verificationCardId = item.getVerificationCardId();
            return String.format("%s,%s", verificationCardId, mappingAsJSONB64);
        };
    }
}
