/*!
  \file
  \brief mot ファイルの転送スレッド

  \author Satofumi KAMIMURA

  $Id$
*/

#include "TransmitThread.h"
#include "Connection.h"
#include <QFile>
#include <string>

using namespace qrk;
using namespace std;


namespace
{
  enum {
    Baudrate = 38400,
  };
}


struct TransmitThread::pImpl
{
  Connection* connection_;
  QString file_;
  size_t file_lines_;
  string device_;


  pImpl(void) : connection_(NULL), file_lines_(0)
  {
  }
};


TransmitThread::TransmitThread(void) : pimpl(new pImpl)
{
}


TransmitThread::~TransmitThread(void)
{
}


void TransmitThread::setSettings(Connection& connection,
                                 const QString& file, size_t file_lines,
                                 const QString& device)
{
  pimpl->connection_ = &connection;
  pimpl->file_ = file;
  pimpl->file_lines_ = file_lines;
  pimpl->device_ = device.toStdString();
}


void TransmitThread::run(void)
{
  QFile file(pimpl->file_);
  if (! file.open(QIODevice::ReadOnly | QIODevice::Text)) {
    emit fail();
    return;
  }

  if (! pimpl->connection_->connect(pimpl->device_.c_str(), Baudrate)) {
    emit fail();
    return;
  }

  size_t send_lines = 0;
  while (! file.atEnd()) {
    QByteArray line = file.readLine();
    pimpl->connection_->send(line.data(), line.count());

    pimpl->connection_->send("\r", 1);
    msleep(2);

    ++send_lines;
    emit percent(static_cast<int>(100.0 * send_lines / pimpl->file_lines_));
  }
  pimpl->connection_->send("\r\n", 2);

  emit success();
}
