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

  \author Satofumi KAMIMURA

  $Id: ConnectionWidgetSample.cpp 506 2009-01-22 12:46:26Z satofumi $
*/

#include "ConnectionWidgetSample.h"
#include "ConnectionWidget.h"
#include <QShortcut>

using namespace std;


struct ConnectionWidgetSample::pImpl
{
  ConnectionWidgetSample* widget_;
  ConnectionWidget connection_widget_;

  vector<string> devices_;
  size_t last_index_;


  pImpl(ConnectionWidgetSample* 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_);
  }
};


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


ConnectionWidgetSample::~ConnectionWidgetSample(void)
{
}


void ConnectionWidgetSample::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 ConnectionWidgetSample::rescanPressed(void)
{
  fprintf(stderr, "rescan pressed.\n");
  pimpl->addDevice();
}
