#include <QEventLoop>
#include <QDebug>
#include "UK1104.h"

UK1104::UK1104(const QString & devname)
 : QextSerialPort(devname),
   valid_connection(false),
   command_running(false) {

   setQueryMode(EventDriven);
   setBaudRate(BAUD115200);
   setDataBits(DATA_8);
   setParity(PAR_NONE);
   setStopBits(STOP_2);
   setFlowControl(FLOW_OFF);
   if (! open(QIODevice::ReadWrite)) {
      return;
   }

   connect(this, SIGNAL(readyRead()),
           this,     SLOT(doRead()));

   connect(&watchdog, SIGNAL(timeout()),
           this,      SLOT(watchdogTimeout()));

   valid_connection = true;
}

UK1104::~UK1104() {
}

bool
UK1104::SendCommand(
   QString command,
   int timeout_milliseconds) {

   if (command_running) {
      return false;
   }
   command_running = true;
   QByteArray rawbuf(command.toAscii());
   rawbuf.append("\r\n");
   write(rawbuf);
   watchdog.setSingleShot(true);
   watchdog.start(timeout_milliseconds);
   return true;
}

bool
UK1104::ValidConnection() {
   return valid_connection;
}

void
UK1104::doRead() {
   QString nxt_data = readAll();
   partial_line.append(nxt_data);
   if (nxt_data.isEmpty()) {

      // Hit EOF, user must have unplugged me.

      valid_connection = false;
      close();
      emitResult(UK1104_CLOSED);
   } else if (partial_line.endsWith("::")) {

      // We have seen the prompt. The command is done, but did it report
      // an error?

      if (partial_line.contains("ERROR :")) {
         emitResult(UK1104_ERROR);
      } else {
         emitResult(UK1104_OK);
      }
   }
}

void
UK1104::watchdogTimeout() {

   // Report timeout from command we tried to run.

   if (command_running) {
      emitResult(UK1104_TIMEOUT);
   }
}

void
UK1104::emitResult(UK1104Errors status) {
   if (watchdog.isActive()) {
      watchdog.stop();
   }
   QString rval = partial_line;
   partial_line.clear();
   command_running = false;
   emit commandDone(status, rval);
}
