#include "QSerialPortUtil.h"

#include <iostream>
#include <QTimer>
#include <QDateTime>
#include "common/utils/QByteUtil.h"
#include "common/utils/SettingConfig.h"

QSerialPortUtil::QSerialPortUtil(QObject *parent) : QObject(parent)
{
    // 其他默认配置
    serial.setDataBits(QSerialPort::Data8);
    serial.setParity(QSerialPort::NoParity);
    serial.setStopBits(QSerialPort::OneStop);
    serial.setFlowControl(QSerialPort::NoFlowControl);
}

void QSerialPortUtil::openSerialPort(QString portName, int baudRate)
{
    serial.setPortName(portName); // 串口名
    serial.setBaudRate(baudRate); // 波特率

    open = serial.open(QIODevice::ReadWrite);

    std::cout << portName.toStdString() << " " << baudRate << " - " << open << std::endl;

    if (SettingConfig::getInstance().WORK_TYPE == "mock")
    {
        // mock data received per second
        QTimer * timer = new QTimer(this);
        connect(timer, &QTimer::timeout,
                this, &QSerialPortUtil::mockReceivData);
        timer->start(1000);
    } else
    {
        if (open == true)
        {
            // 绑定信号与槽
            connect(&serial, &QSerialPort::readyRead,
                    this, &QSerialPortUtil::readData);
        }
    }
}

void QSerialPortUtil::sendData(QByteArray data)
{
    std::cout << data.toStdString() << std::endl;
    if (this->open == true)
    {
        serial.write(data);
    }
}

void QSerialPortUtil::readData()
{
    QByteArray buffer = serial.readAll();

    emit dataRecieved(buffer);
}

bool QSerialPortUtil::isOpen()
{
    return this->open;
}

void QSerialPortUtil::mockReceivData()
{
    QDateTime now = QDateTime::currentDateTime();

    QString frameId = now.toString("HHmmsszzz");

    QByteArray buffer;
    buffer.append(QByteUtil::hexStringToBytes(frameId.mid(0, 8)));

    for (int i = 1; i <= 16; i++)
    {
        int value = qrand() % 10000;
        buffer.append(QByteUtil::hexStringToBytes("00800000")).append(QByteUtil::ULongToBytes(value, 4));
    }

    buffer.append(QByteUtil::hexStringToBytes("EEEEEEEE"));

    emit dataRecieved(buffer);
}
