#include "SerialTool.h"

#include <QDebug>

#include "../global.h"
#include "../logger.h"

// 定义静态成员变量并初始化为 nullptr
SerialTool *SerialTool::instance = nullptr;
QMutex SerialTool::globalMutex;
SerialTool::SerialTool(QObject *parent) : QObject(parent) {}
SerialTool::~SerialTool() {
    if (serialPort.isOpen()) {
        serialPort.close();
    }
}

SerialTool *SerialTool::getInstance(QObject *parent, bool *success) {
    if (instance == nullptr) {
        instance = new SerialTool(parent);
    }
    if (instance->isInUse) {
        if (success) {
            *success = false;
        }
        return nullptr;
    }
    instance->isInUse = true;
    if (success) {
        *success = true;
    }
    //    globalMutex.unlock();
    return instance;
}
// 打开串口的函数
void SerialTool::openSerialPort() {
    const QString portName = firewidgetPort;
    const qint32 baudRate = 9600;

    if (!serialPort.isOpen()) {
        serialPort.setPortName(portName);
        serialPort.setBaudRate(baudRate);

        serialPort.setDataBits(QSerialPort::Data8);
        serialPort.setStopBits(QSerialPort::OneStop);
        serialPort.setParity(QSerialPort::NoParity);
        if (serialPort.open(QIODevice::ReadWrite)) {
            Logger::getInstance().info(QString("串口 %1 打开成功").arg(portName));
            emit serialPortOpened();  // 发射新信号
        } else {
            Logger::getInstance().error(QString("串口 %1 打开错误").arg(portName));
            emit openError();
        }
    }
}

// 关闭串口的函数
void SerialTool::closeSerialPort() {
    if (serialPort.isOpen()) {
        serialPort.close();
        emit openCloseButtonTextChanged("打开串口");
    }
}

bool SerialTool::sendData(const QByteArray &data) {
    if (serialPort.isOpen()) {
        qint64 bytesWritten = serialPort.write(data);
        return bytesWritten == data.size();
    }
    return false;
}

void SerialTool::handleSendDataReques(const QByteArray &data) { sendData(data); }

void SerialTool::readData() {
    QByteArray newData = serialPort.readAll();
    buffer.append(newData);

    int startIndex = buffer.indexOf("\r\n");
    while (startIndex != -1) {
        int endIndex = buffer.indexOf("\r\n", startIndex + 2);
        if (endIndex != -1) {
            QByteArray command = buffer.mid(startIndex + 2, endIndex - startIndex - 2);
            emit dataReceived(newData);
            // 根据 command 的值发射相应的信号
            if (command == "BUTTON_DISABLED") {
                emit disableButtonReceived();
            } else if (command == "BUTTON_PRESSED") {
                emit buttonPressedReceived();
            } else if (command == "BUTTON_ENABLE") {
                emit enableButtonReceived();
            }

            buffer = buffer.mid(endIndex + 2);
        } else {
            break;
        }
        startIndex = buffer.indexOf("\r\n");
    }
}

void SerialTool::setupSerialPort() {
    openSerialPort();
    connect(&serialPort, &QSerialPort::readyRead, this, &SerialTool::readData);
}

void SerialTool::releaseInstance() { isInUse = false; }

bool SerialTool::getIsInUse() { return isInUse; }
