#include "SerialPort.h"
#include "QDebug"

SerialPort::SerialPort() {
  this->serialPort = nullptr;
  this->opened = false;
}

SerialPort::~SerialPort() {}

void SerialPort::portSetup() {
  this->serialPort->setBaudRate(QSerialPort::Baud115200);
  this->serialPort->setFlowControl(QSerialPort::NoFlowControl);
  this->serialPort->setParity(QSerialPort::NoParity);
  this->serialPort->setDataBits(QSerialPort::Data8);
  this->serialPort->setStopBits(QSerialPort::OneStop);
  this->serialPort->setReadBufferSize(2 ^ 24);
}

void SerialPort::requestOpen(QString portName) {
  if (this->serialPort != nullptr) {
    emit openStatus(false);
    return;
  }
  this->serialPort = new QSerialPort(portName);
  this->portSetup();
  if (this->serialPort->open(QIODevice::ReadWrite)) {
    this->opened = true;
    this->serialPort->flush();
    // connect read data callback
    connect(this->serialPort, SIGNAL(readyRead()), this, SLOT(readData()));
    emit openStatus(true);
    return;
  } else {
    delete this->serialPort;
    this->serialPort = nullptr;
    emit openStatus(false);
    return;
  }
}

void SerialPort::requestToStop() {
  this->opened = false;
  this->serialPort->close();
  delete this->serialPort;
  this->serialPort = nullptr;
  emit openStatus(false);
}

void SerialPort::readData() {
  if (this->opened) {
    qint64 availableBytes = 8 * (this->serialPort->bytesAvailable() / 8);
    if (availableBytes > 0) {
      QByteArray received = this->serialPort->read(availableBytes);
      emit newData(received);
    }
  }
}

void SerialPort::requestSend(QByteArray data) {
  if (this->opened) {
    this->serialPort->write(data, data.length());
    this->serialPort->waitForBytesWritten(-1);
  }
}
