package ua.nure.jfn.task4;

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

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;

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

/**
 * @author Dmytro Kolesnykov
 */
public class Part1Test {
	
	private static final InputStream STD_IN = System.in;

	private static final PrintStream STD_OUT = System.out;

	private static final String ENCODING = "UTF-8";

	private static final String EOL_CHAR = "~";

	private static final String[] EMPTY_ARGS = {};

	private static final String INPUT_FILE = "part1.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();
	}

	@ParameterizedTest
	@CsvFileSource(resources = "part1.csv", delimiter = ';')
	void part1(String data, String consoleInput, String expectedLine) throws Exception {
		String expected = toMultiline(expectedLine);
		String input = toMultiline(consoleInput);
		byte[] buf = input.getBytes(ENCODING);
		ByteArrayInputStream bais = new ByteArrayInputStream(buf);
		System.setOut(out);
		System.setIn(bais);
		String actual = "";
		byte[] content = null;
		try {
			content = Utils.getContent(INPUT_FILE);
			Utils.saveContent(INPUT_FILE, toMultiline(data).getBytes(ENCODING));

			Part1.main(EMPTY_ARGS);

			out.flush();
			actual = baos.toString();
		} finally {
			System.setOut(STD_OUT);
			System.setIn(STD_IN);
			Utils.saveContent(INPUT_FILE, content);
		}
		assertEquals(expected.trim(), actual.trim());
	}

}
