package WorkoutDatesUpdater;

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

public class logging {

    public static final String indent = " ".repeat(22);
    public static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void checkLogExists() throws IOException {
        File log = getLogFile();
        if (log.exists()){
            File newLog = new File("logs/oldLog.log");
            if (newLog.exists()){
                newLog.delete();
            }
            log.renameTo(newLog);
            log = getLogFile();
            FileWriter writer = new FileWriter(log, false);
            writer.write("");
            writer.close();
        }
    }

    public static File getLogFile(){
        return new File("logs/log.log");
    }

    public static void setLog(String text, boolean addDate, boolean addIndent) throws IOException {
        String resultText = "";
        if (addIndent) {
            resultText += indent;
        }
        if (addDate) {
            resultText += getCurrentTime();
        }
        resultText += text;
        System.out.println(resultText);
        File log = getLogFile();
        FileWriter writer = new FileWriter(log, true);
        writer.write(resultText + "\n");
        writer.close();
    }

    public static void logException(Exception e) throws IOException {
        setLog("Error: " + e.getMessage(), true, false);
        setLog("Error trace:", false, true);
        for (StackTraceElement line : e.getStackTrace()){
            setLog(line.toString(), false, false);
        }
    }

    public static String getCurrentTime(){
        java.util.Date currentDate = new Date(System.currentTimeMillis());
        return "[" + df.format(currentDate) + "] ";
    }

}
