package Common.Utils;
import Common.Visual.UI_;

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 PrintException(Exception ex) {
        StringWriter out = new StringWriter();
        PrintWriter writer = new PrintWriter(out);
        ex.printStackTrace(writer);
        writer.flush();
        Print(out.toString());
        if (UI_.isActive())
            UI_.Error("Возникло исключение. Подробности в файле журнала\n" +
                    Utils_.Brackets(getLogFile().getAbsolutePath()));
    }
}
