package ua.nure.jfn.task4;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;

/**
 * @author Dmytro Kolesnykov
 */
public class Part4Test {

	private static final InputStream STD_IN = System.in;

	private static final PrintStream STD_OUT = System.out;

	private static final String EOL_CHAR = "~";

	private static final String[] EMPTY_ARGS = {};

	private static final String INPUT_FILE = "part4.txt";

	private static final String EOL = System.lineSeparator();

	private final ByteArrayOutputStream baos = new ByteArrayOutputStream();

	private final PrintStream out = new PrintStream(baos);

	private static String toMultiline(String line) {
		return line.replaceAll(EOL_CHAR, EOL).trim();
	}
	
	@AfterAll
	static void tearDown() throws IOException {
		Files.deleteIfExists(Path.of(INPUT_FILE));
	}

	@ParameterizedTest
	@CsvFileSource(resources = "part4.csv", delimiter = ';')
	void part4(String inputData, String expected) throws Exception {
		Files.writeString(Paths.get(INPUT_FILE), inputData);
		System.setOut(out);
		String actual = "";
		try {
			Part4.main(EMPTY_ARGS);
			
			out.flush();
			actual = baos.toString();
		} finally {
			System.setOut(STD_OUT);
			System.setIn(STD_IN);
		}
		assertEquals(toMultiline(expected).trim(), actual.trim());
	}

}
