/**
 *
 */
package utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Archivo de de registro que permite mostrar el paso de mensajes entre el ECR, Java y el PinPad
 *
 * @author diego
 *
 */
//marco
public class SimpleLogger {
	private FileOutputStream fileOutput;
	private PrintStream printStream;
	private Calendar runDate = null;
	private String logDir = "log";
	private String fileName = "";
	private String version = "3.3.2";

	public SimpleLogger() {
		this.runDate = Calendar.getInstance();
		this.fileName = "simple_" + this.logDir + this.runDate.get(1);

		if (this.runDate.get(2) + 1 < 10) {
			this.fileName = (this.fileName + "0" + (this.runDate.get(2) + 1));
		} else {
			this.fileName += this.runDate.get(2) + 1;
		}

		if (this.runDate.get(5) < 10)
			this.fileName = (this.fileName + "0" + this.runDate.get(5));
		else {
			this.fileName += this.runDate.get(5);
		}
		this.fileName += ".txt";
		String longFileName=null;
		String home=null;
		try {
		      OSValidator osv = new OSValidator();
		      
		      if (osv.isWindows()){
		    	  longFileName = this.logDir + "\\" + this.fileName;
		    	  home = System.getenv("homepath");
		    	  home = home + "\\java\\emv2000-64\\bin\\";
		    	  longFileName= home + longFileName;
		      } else {
		    	  longFileName = this.logDir + "/" + this.fileName;
		      }
		
			//String longFileName = this.logDir + "/" + this.fileName;
			this.fileOutput = new FileOutputStream(longFileName, true);
			this.printStream = new PrintStream(this.fileOutput);
			printStream("------Inicio de transacción _ Abriendo SimpleLogger------------");
		} catch (Exception e) {
			System.out.println("Cannot create log file " + this.fileName + " on directory " + this.logDir + " " + e.getMessage());
			System.out.println("archivo FileLogger: " + longFileName);
			System.exit(1);
		}
	}

	public void printStream(String s) {
		this.printStream.println(new SimpleDateFormat("HH:mm:ss dd/MM/yyyy").format(new Date()) + "  v" + version + "\t" + s);
		this.printStream.flush();
	}

	public void closeLogger() {
		printStream("------Fin de transacción _ Cerrando SimpleLogger------------");
		this.printStream.close();
		try {
			this.fileOutput.close();
		} catch (IOException e) {
			System.out.println("Caution! output file " + this.fileName + " might not be correctly closed, system resource might not be completely freed.");
		}
	}

	public void printStream(String string, Throwable e) {
		this.printStream.println(new SimpleDateFormat("HH:mm:ss dd/MM/yyyy").format(new Date()) + "  v" + version + "\t" + stackTraceToString(e));
		this.printStream.flush();
	}

	public String stackTraceToString(Throwable e) {
		StringBuilder sb = new StringBuilder();
		for (StackTraceElement element : e.getStackTrace()) {
			sb.append(element.toString());
			sb.append("\n");
		}
		return sb.toString();
	}
}
