/*
 * 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.junit.Assert;
import org.junit.Test;
import org.springframework.batch.item.ItemWriter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

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

public class CompositeOutputWriterTest {

    private CompositeOutputWriter sut;

    @Test
    public void writeIntoQueueAllItems() throws Exception {

        //given
       List<GeneratedVotingCardOutput> inputItems = new ArrayList<>();
        inputItems.add(createOutput());
        inputItems.add(createOutput());
        inputItems.add(createErrorOutput());
        inputItems.add(createOutput());

        List<GeneratedVotingCardOutput> outputItems = new ArrayList<>();
        ListOutputItemWriter listOutputItemWriter = new ListOutputItemWriter(outputItems);

        sut = new CompositeOutputWriter();
        sut.setDelegates(Collections.singletonList(listOutputItemWriter));
        sut.write(inputItems);

        //then
        Assert.assertTrue(outputItems.size() < inputItems.size());
        //assert no error items in output
        outputItems.forEach(item -> Assert.assertFalse(item.isError()));

    }

    private GeneratedVotingCardOutput createOutput() {
        return GeneratedVotingCardOutput.success(null,null,null,null,null,null,null,null,null, null, null,null,null);
    }

    private GeneratedVotingCardOutput createErrorOutput() {
        return GeneratedVotingCardOutput.error(new Exception("For testing purposes only"));
    }



    private class ListOutputItemWriter implements ItemWriter<GeneratedVotingCardOutput> {

        private List<GeneratedVotingCardOutput> list;

        public ListOutputItemWriter(final List<GeneratedVotingCardOutput> list) {
            this.list = list;
        }
        @Override
        public void write(final List<? extends GeneratedVotingCardOutput> items) throws Exception {
            items.forEach(item -> list.add(item));
        }
    }
}
