package com.uavps.framework.udp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author allen
 */

public enum TaskInfo {
    // 枚举实例，包含初始化坐标和转化比率
    INSTANCE(0.0f, 0.0f, true, 1.0f);

    // 枚举字段
    private double x;
    private double y;
    private boolean initFlag;
    private double conversionRate;
    private final int initCenterPixel = 500;
    private Long bizId;
    private String filePath;
    private Long lastTime = 0L;

    private FileWriterThread writerThread;

    // 用于存储待写入的UDP包数据
    private final BlockingQueue<LogEntry> logQueue = new LinkedBlockingQueue<>();

    // 枚举构造函数
    private TaskInfo(float x, float y, boolean initFlag, float conversionRate) {
        this.x = x;
        this.y = y;
        this.initFlag = initFlag;
        this.conversionRate = conversionRate;
    }

    // 重置方法
    public void reset(Long bizId, String filePath) {
        // 初始化
        this.x = 0f;
        this.y = 0f;
        this.initFlag = true;
        this.conversionRate = 0.00018;
        this.bizId = bizId;
        this.filePath = filePath;
        logQueue.clear();
        if(writerThread != null) {
            writerThread.shutdown();
            try {
                writerThread.join(); // 等待写入线程完成
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        writerThread = new FileWriterThread();
        writerThread.start();
    }

    // 日志条目类
    public static class LogEntry {
        final String data;
        final long time;

        LogEntry(String data, long time) {
            this.data = data;
            this.time = time;
        }
    }

    // 文件写入线程
    private class FileWriterThread extends Thread {
        private volatile boolean running = true;

        @Override
        public void run() {
            File file = new File(filePath);

            // 创建父目录（如果不存在）
            File parentDir = file.getParentFile();
            if (!parentDir.exists()) {
                parentDir.mkdirs(); // 创建所有必要的父目录
            }
            try (FileOutputStream fos = new FileOutputStream(TaskInfo.INSTANCE.getFilePath(), true)) {
                while (running || !logQueue.isEmpty()) {
                    LogEntry entry = logQueue.take(); // 阻塞直到有数据
                    // 格式化时间戳(10位数字 + 冒号)
                    String timestamp = String.format("%010d:", entry.time);
                    // 先写入时间戳
                    fos.write(timestamp.getBytes());
                    // 再写入实际数据
                    fos.write(entry.data.getBytes());
                    // 可选: 每条记录后加换行
                    fos.write('\n');
                    fos.flush();
                }
            } catch (IOException | InterruptedException e) {
                if (running) { // 仅在非正常关闭时打印错误
                    System.err.println("File writer error: " + e.getMessage());
                }
            }
        }

        public void shutdown() {
            running = false;
            this.interrupt(); // 中断阻塞的take操作
        }
    }

    // Getter和Setter方法
    public double getX() {
        return x;
    }

    public void setX(double x) {
        this.x = x;
    }

    public double getY() {
        return y;
    }

    public void setY(double y) {
        this.y = y;
    }

    public boolean getInitFlag() {
        return initFlag;
    }

    public void setInitFlag(boolean initFlag) {
        this.initFlag = initFlag;
    }

    public double getConversionRate() {
        return conversionRate;
    }

    public void setConversionRate(float conversionRate) {
        this.conversionRate = conversionRate;
    }

    // 转换坐标方法
    public double convertValue(float value) {
        return value * conversionRate;
    }

    public double getConversionCenterPixel() {
        return initCenterPixel * conversionRate;
    }

    public Long getBizId() {
        return bizId;
    }

    public void setBizId(Long bizId) {
        this.bizId = bizId;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public boolean isInitFlag() {
        return initFlag;
    }

    public int getInitCenterPixel() {
        return initCenterPixel;
    }

    public Long getLastTime() {
        return lastTime;
    }

    public void setLastTime(Long lastTime) {
        this.lastTime = lastTime;
    }

    public BlockingQueue<LogEntry> getLogQueue() {
        return logQueue;
    }

    public FileWriterThread getWriterThread() {
        return writerThread;
    }

    public void setWriterThread(FileWriterThread writerThread) {
        this.writerThread = writerThread;
    }

    // 显示坐标信息
    public void displayCoordinates() {
        System.out.printf("%s 坐标系 - X: %.2f, Y: %.2f (初始化标识: %s, 转化比率: %.6f)%n",
                this.name(), x, y, initFlag, conversionRate);
    }
}
