package com.aps.common.util;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class FileHelper {
    private static final String LOG_FILE = "schedule_log.txt";
    private static final String LOG_FILE_PATH = "log/";

    // 日志级别
    private static final int LOG_LEVEL_DEBUG = 0;
    private static final int LOG_LEVEL_INFO = 1;
    private static final int LOG_LEVEL_WARN = 2;
    private static int currentLogLevel = LOG_LEVEL_INFO;

    // 局部搜索优化

    public static void log(String message) {
        log(message, LOG_LEVEL_INFO, true);
    }

    public static void log(String message, boolean enableLogging) {
        log(message, LOG_LEVEL_INFO, enableLogging);
    }

    public static void log(String message, int level) {
        log(message, level, false);
    }

    public static void log(String message, int level, boolean enableLogging) {
        if (enableLogging && level >= currentLogLevel) {
            writeLogFile(message);
        }
    }

    public static void writeLogFile(String message) {
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))+"-";

        // 确保目录存在
        java.io.File logDir = new java.io.File(LOG_FILE_PATH);
        if (!logDir.exists()) {
            logDir.mkdirs(); // 创建目录（包括父目录）
        }

        String filePath = LOG_FILE_PATH + date + LOG_FILE;

        try (PrintWriter writer = new PrintWriter(new FileWriter(filePath, true))) {
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
            writer.println("[" + timestamp + "] " + message);
            System.out.println("[" + timestamp + "] " + message);

        } catch (IOException e) {
            System.err.println("Failed to write log: " + e.getMessage());
        }
    }

    public static void writeFile(String message,String fileDir,String fileName) {
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))+"-";

        // 确保目录存在
        java.io.File logDir = new java.io.File(fileDir);
        if (!logDir.exists()) {
            logDir.mkdirs(); // 创建目录（包括父目录）
        }

        String filePath = fileDir + date + fileName;

        try (PrintWriter writer = new PrintWriter(new FileWriter(filePath, true))) {

            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
            writer.println("[" + timestamp + "] " + message);
            System.out.println("[" + timestamp + "] " + message);

        } catch (IOException e) {
            System.err.println("Failed to write log: " + e.getMessage());
        }
    }

    public static void writeFile(String message,String fileName) {

        writeFile(message,LOG_FILE_PATH,fileName);
    }

}