package com.yztiot.streetlamp;

import android.util.Log;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class SerialManage {

    private static SerialManage instance;
    private ScheduledExecutorService scheduledExecutor;
    private SerialHandle serialHandle;
    private Queue<String> queueMsg = new ConcurrentLinkedQueue<String>();
    private ScheduledFuture sendStrTask;
    private boolean isConnect = false;
    private String currentSerialPath ;

    private SerialManage() {
        scheduledExecutor = Executors.newScheduledThreadPool(8);
    }

    public static SerialManage getInstance() {
        if (instance == null) {
            synchronized (SerialManage.class) {
                if (instance == null) {
                    instance = new SerialManage();
                }
            }
        }
        return instance;
    }

    // 获取线程池
    public ScheduledExecutorService getScheduledExecutor() {
        return scheduledExecutor;
    }
    public void updateSerialPath(String newPath, String baudrateStr) {
        this.currentSerialPath = newPath;

        if (serialHandle == null) {
            serialHandle = new SerialHandle();  // 确保 serialHandle 被初始化
        }

        if (isConnect) {
            close();
            int baudrate;
            try {
                baudrate = Integer.parseInt(baudrateStr);
            } catch (NumberFormatException e) {
                Log.e("SerialManage", "波特率格式错误: " + baudrateStr);
                return;
            }
            open(newPath, baudrate, 8, 1, 0);
        }
    }

    // 串口初始化
    public void init(SerialInter serialInter) {
        if (serialHandle == null) {
            serialHandle = new SerialHandle();
            startSendTask();  // 初始化后启动任务
        }
        serialHandle.addSerialInter(serialInter);
    }


    // 打开串口
    public boolean open(String path, int baudrate, int dataBits, int stopBits, int parity) {
        if (serialHandle == null) {
            Log.e("SerialManage", "SerialHandle 未初始化");
            return false;
        }
        boolean isOpened = serialHandle.open(path, baudrate, dataBits, stopBits, parity, true);
        isConnect = isOpened;

        if (isOpened) {
            startSendTask();  // 串口打开成功后启动发送任务
        }

        return isOpened;
    }


    // 发送指令
    public void send(String msg) {
//        Log.d("SerialManage", "将普通字符串指令放入队列中，等待发送：" + msg);
        queueMsg.offer(msg);  // 普通字符串直接放入队列
    }

    // 关闭串口
    public void close() {
        if (serialHandle != null) {
            serialHandle.close();
        } else {
            Log.w("SerialManage", "close() called, but serialHandle is null.");
        }
    }

    // 启动发送任务
    private void startSendTask() {
        cancelSendTask();
        sendStrTask = scheduledExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!isConnect) {
                    return;  // 如果没有连接，不执行发送
                }
                if (serialHandle == null) {
                    return;  // 如果串口对象为空，不执行发送
                }
                String msg = queueMsg.poll();  // 获取列队消息
                if (msg == null || "".equals(msg)) {
                    return;  // 如果队列为空，不执行发送
                }
                serialHandle.send(msg);  // 发送消息
            }
        }, 0, 100, TimeUnit.MILLISECONDS);  // 每 100 毫秒检查一次
    }

    // 取消发送任务
    private void cancelSendTask() {
        if (sendStrTask == null) return;
        sendStrTask.cancel(true);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        sendStrTask = null;
    }

    public boolean isConnect() {
        return isConnect;
    }
}
