package ei.engine.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;

/**
 * @author Ziver
 * this class kan print strings to multiple PrintStreams
 */
public class MultiPrintStream extends PrintStream {
	//the printstreams that will print
	private PrintStream[] streams;
	//a instance of this class
	public static MultiPrintStream out;
	
	/**
	 * this constructor makes a simple PrintStream that prints to the console and to a file
	 * @param file the file name to outpu to
	 */
	public MultiPrintStream(String file){
		super(new PrintStream(System.out));
		try {
			streams = new PrintStream[2];
			streams[0] = new PrintStream(System.out);
			streams[1] = new PrintStream(new File(file));
		} catch (FileNotFoundException e) {
			System.out.println("Error when declaring PrintStream!!");
			e.printStackTrace();
		}
	    
	}

	/**
	 * this constructor takes a array of PrintStreams to be used
	 * @param streams a array of the streams that will be used
	 */
	public MultiPrintStream(PrintStream[] streams){
	    super(streams[0]);
	    this.streams = streams;
	}
	
	/**
	 * this constructor takes a array of PrintStreams to be used
	 * @param streams a array of the streams that will be used
	 */
	public static void makeInstance(MultiPrintStream instanceStream){
		out = instanceStream;
	}
	
	public boolean checkError(){
		for(int i=0; i<streams.length ;i++)
			if(streams[i].checkError())
				return true;
		return false;
	}

	
	/**
	 * closes all the PrintStreams
	 */
	public void close(){
		for(int i=0; i<streams.length ;i++)
			streams[i].close();
	}

	/**
	 * prints whit a new line to all the PrintStreams
	 */
	public void println(String s){
		if(!s.equals(""))s = getTime() + s;
		for(int i=0; i<streams.length ;i++)
			streams[i].println(s);
	}
	
	/**
	 * prints to all the PrintStreams
	 */
	public void print(String s){
		for(int i=0; i<streams.length ;i++)
			streams[i].print(s);
	}
	
	private String getTime(){
		return "" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS # ")).format(new java.util.Date());
	}
}
