package omq.common.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import omq.exception.EnvironmentException;

public class Log {

	public static void saveLog(String processName, byte[] bytesResponse) throws IOException {
		try {
			Properties env = Environment.getEnvironment();

			String debugPath = env.getProperty(ParameterQueue.DEBUGFILE, "");
			if (debugPath.length() > 0) {
				long timeNow = (new Date()).getTime();

				File outputFolder = new File(debugPath + File.separator);
				outputFolder.mkdirs();
				
//				File outputFolder = new File(debugPath + File.separator + processName);
//				outputFolder.mkdirs();

//				File outputFileContent = new File(outputFolder.getAbsoluteFile() + File.separator + "content_" + timeNow);
//				FileOutputStream outputStream = new FileOutputStream(outputFileContent);
//				IOUtils.write(bytesResponse, outputStream);
//				outputStream.close();

				File outputFileLog = new File(debugPath + File.separator + "log");
				boolean exist = outputFileLog.exists();
				
				FileWriter fw = new FileWriter(outputFileLog, true); // the true will append the new data
				if(!exist){
					fw.write("#ProcessName\t\tFile\t\t\t\t\tDate\t\t\tSize\n");
				}
				fw.write(processName + "\t" + "content_" + timeNow + "\t" + timeNow + "\t" + bytesResponse.length + "\tbytes\n");
				fw.close();
			}
		} catch (EnvironmentException e) {
			throw new IOException(e.getMessage(), e);
		}
	}
	
	public static void saveTimeSendRequestLog(String processName, String coorId, String method, long timeNow) throws IOException {
		try {
			Properties env = Environment.getEnvironment();

			String debugPath = env.getProperty(ParameterQueue.DEBUGFILE, "");
			if (debugPath.length() > 0) {			
				File outputFolder = new File(debugPath + File.separator + processName);
				outputFolder.mkdirs();
				
				File outputFileLog = new File(outputFolder + File.separator + "log");
				boolean exist = outputFileLog.exists();
				
				FileWriter fw = new FileWriter(outputFileLog, true); // the true will append the new data
				if(!exist){
					fw.write("#CoorId\tMethod\tDate\n");
				}
				fw.write(coorId + "\t" + method + "\t" + timeNow + "\n");
				fw.close();
			}
		} catch (EnvironmentException e) {
			throw new IOException(e.getMessage(), e);
		}
	}	
}
