import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

public class TestWriter {

	private boolean isMultiTest;
	private int done;

	private String prefix;
	private boolean isOpened;
	private PrintWriter out;
	private int printedTests;
	private int countTests = 0;

	public TestWriter(boolean isMultiTest, String prefix) {
		this.isMultiTest = isMultiTest;
		this.prefix = prefix;
		this.done = 0;
	}

	public void init(int n) throws FileNotFoundException {
		printedTests = 0;
		if (isOpened) {
			throw new AssertionError("Please close prevoius multitest");
		}
		isOpened = true;
		countTests = n;
		done++;
		out = new PrintWriter(prefix + ((done < 10) ? "0" : "")
				+ String.valueOf(done));
		if (isMultiTest) {
			out.println(countTests);
		}
	}

	public void close() {
		if (!isOpened) {
			System.err.println("Before closing test was not created");
		}
		isOpened = false;
		if (printedTests != countTests) {
			throw new AssertionError("Wrong number of tests: all: "
					+ countTests + " printed: " + printedTests);
		}
		out.close();
	}

	public void printTest(Object test) throws IOException {
		if (!isMultiTest) {
			throw new AssertionError("Multi test doesn't allowed");
		}
		if (!isOpened) {
			throw new AssertionError("Please create test");
		}
		printedTests++;
		out.println(test.toString());
	}

	public void printSimpleTest(Object test) throws IOException {
		init(1);
		printedTests++;
		out.print(test.toString());
		close();
	}
}
