/*!
  \file
  \brief SerialConnectionWidget の動作確認ウィジット

  \author Satofumi KAMIMURA

  $Id: SerialConnectionWidgetSample.cpp 1979 2012-04-05 16:26:14Z satofumi $
*/

#include "SerialConnectionWidgetSample.h"
#include "SerialConnectionWidget.h"
#include <QShortcut>
#include <cstdio>

using namespace qrk;
using namespace std;


struct SerialConnectionWidgetSample::pImpl
{
  SerialConnectionWidgetSample* widget_;
  SerialConnectionWidget connection_widget_;

  vector<string> devices_;
  size_t last_index_;


  pImpl(SerialConnectionWidgetSample* widget)
    : widget_(widget), connection_widget_(widget), last_index_(0)
  {
  }


  void initializeForm(void)
  {
    // ウィジット
    widget_->connection_dummy_label_->hide();
    widget_->main_layout_->addWidget(&connection_widget_);

    // コンポーネント
    connect(&connection_widget_,
            SIGNAL(connectRequest(bool, const std::string&)),
            widget_, SLOT(connectPressed(bool, const std::string&)));
    connect(&connection_widget_, SIGNAL(rescanRequest()),
            widget_, SLOT(rescanPressed()));

    // Ctrl-q で終了させる
    (void) new QShortcut(Qt::CTRL + Qt::Key_Q, widget_, SLOT(close()));
  }


  void addDevice(void)
  {
    char buffer[13];
    snprintf(buffer, 13, "%d", last_index_++);

    devices_.push_back("device: " + string(buffer));
    connection_widget_.setDevices(devices_);
  }
};


SerialConnectionWidgetSample::SerialConnectionWidgetSample(QWidget* parent)
  : QWidget(parent), pimpl(new pImpl(this))
{
  setupUi(this);
  pimpl->initializeForm();
}


SerialConnectionWidgetSample::~SerialConnectionWidgetSample(void)
{
}


void SerialConnectionWidgetSample::connectPressed(bool connection,
                                            const string& device)
{
  if (connection) {
    fprintf(stderr, "connect request: %s\n", device.c_str());

  } else {
    fprintf(stderr, "disconnect request\n");
  }

  // 接続、切断、の要求を成功扱いにする
  pimpl->connection_widget_.setConnected(connection);
}


void SerialConnectionWidgetSample::rescanPressed(void)
{
  fprintf(stderr, "rescan pressed.\n");
  pimpl->addDevice();
}
