package com.connor.mail;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogUtils {

	private static String path =  "D:\\Siemens\\Teamcenter12\\bin\\";
	private static SimpleDateFormat DateFormat_filename=new SimpleDateFormat("yyyyMMdd");
	private static SimpleDateFormat DateFormat_context=new SimpleDateFormat("yyyyMMdd HH:mm:ss");
	private BufferedWriter bw;
	private String clazzStr;
	
	public LogUtils(Class clazz) {
		// TODO Auto-generated constructor stub
		clazzStr = clazz.toString();
	}

	public void createLogFile(String filename){
		try {
			String logPath = path  + DateFormat_filename.format(new Date()) + filename;
			System.out.println("logPath = "+logPath);
			if(FileUtils.createFile(logPath)){
				FileWriter fw = new FileWriter(logPath,true);
				bw = new BufferedWriter(fw);  
				start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} 
		
	}
	
	public void info(String context){
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		sb.append(DateFormat_context.format(new Date()));
		sb.append(" info");
		sb.append("]   ");
		sb.append(context);
		try {
			bw.newLine();
			bw.write(sb.toString());
			bw.flush();
			System.out.println(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void error(String context){
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		sb.append(DateFormat_context.format(new Date()));
		sb.append(" error");
		sb.append("]   ");
		sb.append(context);
		try {
			bw.newLine();
			bw.write(sb.toString());
			bw.flush();
			System.out.println(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	
	public void start(){
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		sb.append(DateFormat_context.format(new Date()));
		sb.append("]   ");
		sb.append(clazzStr);
		sb.append(".start");
		try {
			bw.newLine();
			bw.newLine();
			bw.newLine();
			bw.newLine();
			bw.write(sb.toString());
			bw.flush();
			System.out.println(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	public void end(){
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		sb.append(DateFormat_context.format(new Date()));
		sb.append("]   ");
		sb.append(clazzStr);
		sb.append(".end");
		try {
			bw.newLine();
			bw.write(sb.toString());
			bw.flush();
			System.out.println(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void closeLogFile(){
		if(bw!=null){
			try {
				end();
				bw.flush();
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	
}
