package no.valg.valgnatt.database.forberedvalg;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static java.util.Comparator.reverseOrder;
import static no.valg.valgnatt.common.ThrowingConsumer.throwingConsumerWrapper;
import static org.junit.Assert.assertArrayEquals;

public class ForberedValgTest {

    private static final Path FAKTISK = Paths.get("src/test/resources/db/initialdata/full_2017");
    private static final Path FORVENTET = Paths.get("src/test/resources/db/initialdata/forventet_full_2017");

    @Before
    public void setUp() throws Exception {
        opprettOutputKatalog();
    }

    private void opprettOutputKatalog() throws IOException {
        Files.createDirectory(FAKTISK);
    }

    @After
    public void tearDown() throws Exception {
        slettGamleFiler();
    }

    private void slettGamleFiler() throws IOException {
        if (Files.exists(FAKTISK)) {
            Files.walk(FAKTISK)
                    .sorted(reverseOrder())
                    .forEach(throwingConsumerWrapper(Files::delete));
        }
    }

    @Test
    public void main_oppretterForventedeCsvFiler() throws IOException {
        ForberedValg.main(new String[]{"test"});
        sjekkLikeFiler();
    }

    private void sjekkLikeFiler() throws IOException {
        Files.list(FORVENTET).forEach(throwingConsumerWrapper(ForberedValgTest::sjekkForventetFilMotFaktiskFil));
    }

    private static void sjekkForventetFilMotFaktiskFil(Path path) throws IOException {
        Path fileName = path.getFileName();
        assertArrayEquals(fileName.toString(), Files.readAllBytes(path), Files.readAllBytes(FAKTISK.resolve(fileName)));
    }

}
