package jnet.lib;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LogFile {

    // nazev souboru
    private static final String outFile = "log.log";
    // zapisovat i log do console
    private static boolean consoleLog = true;
    // format datumu a casu
    private static String dateFormat = "dd.MM.YY HH:m:ss";
    // debug rezim
    private static boolean debug = false;

    private static File out = new File(outFile);

    private static final DateFormat df = new SimpleDateFormat(dateFormat);

    private static void write(Object text, boolean line) {
        
        String date = df.format(new Date());

        try {
            if (!out.exists()) {
                out.createNewFile();
            }
            PrintWriter pwOut = new PrintWriter(new FileOutputStream(out, true), true);
            pwOut.print(date);
            pwOut.write("\t");
            if (line) {
                pwOut.println(text);
            } else {
                pwOut.print(text);
            }
            pwOut.close();

            LogWindow.addRow(date + "\t" + text.toString());

        } catch (Exception ex) {
            Logger.getLogger(LogFile.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public static void printErr(String line) {
        write("E\t" + line, true);
        if (consoleLog) {
            System.err.println(line);
        }
    }

    public static void printInfo(String line) {
        write("I\t" + line, true);
        if (consoleLog) {
            System.out.println(line);
        }
    }

    public static void printDebug(String line) {
        write("D\t" + line, true);
        if (debug) {
            if (consoleLog) {
                System.out.println(line);
            }
        }

    }

    public static void clear() {
        try {
            out.delete();
        } catch (Exception ex) {
            Logger.getLogger(LogFile.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void setDebug(boolean b) {
        debug = b;
    }

}
