package Visual_DVM_2021.UI.Interface;
import Common.Current;
import Common.UI.DebugPrintLevel;
import Common.UI.UI;
import Common.Utils.Utils;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Paths;
import java.util.Date;
public interface Loggable {
    String getLogHomePath();
    String getLogName();
    default File getLogFile() {
        return Paths.get(getLogHomePath(), (getLogName() + "_log.txt")).toFile();
    }
    default void ClearLog() {
        try {
            Utils.forceDeleteWithCheck(getLogFile());
        } catch (Exception ignored) {
        }
    }
    default void Print(String message) {
        try {
            FileWriter Log = new FileWriter(getLogFile(), true);
            String datedMessage = Utils.Brackets(new Date()) + " " + message;
            Log.write(datedMessage + "\n");
            Log.close();
        } catch (Exception ignored) {
        }
    }
    default void Print(DebugPrintLevel level, String message) {
        if (level.isEnabled())
            Print(Utils.Brackets(level.getDescription()) + " " + message);
    }
    default void PrintException(Exception ex) {
        StringWriter out = new StringWriter();
        PrintWriter writer = new PrintWriter(out);
        ex.printStackTrace(writer);
        writer.flush();
        Print(out.toString());
        if (Current.hasUI())
            UI.Error("Возникло исключение. Подробности в файле журнала\n" +
                    Utils.Brackets(getLogFile().getAbsolutePath()));
    }
}
