package com.imdroid.common.util;

import java.util.concurrent.ExecutorService;

import java.io.*;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

public class WarningLogExecutor {
    private final String logDirectory;
    private final ExecutorService executor;

    public WarningLogExecutor(String logDirectory) {
        this.logDirectory = logDirectory;
        this.executor = ThreadManager.getSingleThreadPool("warning_log_thread");
    }

    public void generateWarningLogs(String keyword, String warningTypeName) {
        // 单线程处理，防止数据写入混乱
        executor.submit(() -> searchLogsForDeviceID(this.logDirectory, keyword, warningTypeName));
    }

    public static void searchLogsForDeviceID(String dirPath, String deviceId, String warningType) {
        try {
            // 判断目录是否存在，一般写在 application.properties 中
            File dir = new File(dirPath);
            if (!dir.exists() || !dir.isDirectory()) {
                return;
            }

            // 只收集一小时内的日志，否则太影响性能
            long oneHourAgo = System.currentTimeMillis() - 3600000;
            File[] files = dir.listFiles((d, name) -> name.startsWith("sideslopertcm"));


            if (files != null && files.length > 0) {
                Arrays.sort(files, (f1, f2) -> Long.compare(f2.lastModified(), f1.lastModified()));

                StringBuilder processedFiles = new StringBuilder();
                for (File file : files) {
                    if (file.lastModified() >= oneHourAgo) {
                        processedFiles.append(String.format("%s\n", file.getName()));
                    }
                }

                if (processedFiles.length() == 0) {
                    return;
                }

                // 文件名的日期只保存年月日，当天重复触发会新的覆盖旧的
                String date = DateTimeFormatter.ofPattern("yyyyMMdd")
                        .format(LocalDateTime.now());
                String outputFileName = String.format("%s/Warning_%s_%s_%s.log", dirPath,deviceId,date, warningType);

                try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName))) {
                    writer.write("=== 搜索信息 ===\n");
                    writer.write("处理时间: " + LocalDateTime.now() + "\n");
                    writer.write("搜索目录: " + dirPath + "\n");
                    writer.write("设备ID: " + deviceId + "\n");
                    writer.write("警告类型: " + warningType + "\n\n");

                    writer.write("=== 处理文件列表 ===\n");
                    writer.write(processedFiles.toString());
                    writer.write("\n=== 匹配结果 ===\n");

                    for (File file : files) {
                        if (file.lastModified() >= oneHourAgo) {
                            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                                String line;
                                while ((line = reader.readLine()) != null) {
                                    if (line.contains(deviceId)) {
                                        writer.write(String.format("[%s] %s\n",
                                                file.getName(), line));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}