package com.munjaon.client.util;

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

/**
 * 로깅 관련 유틸리티 클래스
 * @author JDS
 */
public class LogUtil {

    private final static String sTimeFormat = "[HH:mm:ss.SSS] ";
    private final static String sDateFormat = "_yyyyMMdd";
    private final static String sFileExt = ".log";

    private PrintWriter out;
    private String sLogFile;
    private String sDate;

    public LogUtil(String sLogFile) {
        this.sLogFile = sLogFile;

        if ( sLogFile != null ) {
            FileUtil.mkdirs(sLogFile, true);
        }
    }

    private void open() {
        close();

        if (sLogFile != null) {
            try {
                out = new PrintWriter( new BufferedWriter( new FileWriter(sLogFile + sDate + sFileExt, true) ), true );
            } catch(Exception e) {
                out = null;
            }
        }

        if( out == null ) {
            out = new PrintWriter(System.out, true);
        }
    }

    public void close() {
        if (sLogFile != null && out != null) {
            try {
                out.close();
                out = null;
            } catch (Exception e) {
            }
        }
    }

    public static void log(String sFile, Object oLog) {
        LogUtil logger = new LogUtil(sFile);
        logger.log(oLog);
        logger.close();
    }

    public synchronized void log(Object oLog) {
        SimpleDateFormat sdf = new SimpleDateFormat();
        Date date = new Date();

        sdf.applyPattern(sDateFormat);
        String sDates = sdf.format(date);

        sdf.applyPattern(sTimeFormat);
        String sTime = sdf.format(date);

        try {
            if (!sDates.equals(this.sDate)) {
                this.sDate = sDates;
                open();
            }

            if (oLog instanceof Exception) {
                out.print( sTime );
                ((Exception)oLog).printStackTrace(out);

                if (sLogFile == null) {
                    ((Exception)oLog).printStackTrace();
                }
            } else {
                out.println( sTime + oLog );
            }

            out.flush();
        } catch ( Exception e ) {
            close();
        }
    }
}
