package omq.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import omq.exception.EnvironmentException;

import org.apache.commons.io.IOUtils;

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 + 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);
		}
	}
}
