/*!
  \file
  \brief 接続管理ウィジット

  \author Satofumi KAMIMURA

  $Id: ConnectionWidget.cpp 1105 2009-07-01 13:12:51Z satofumi $
*/

#include "ConnectionWidget.h"

using namespace std;


struct ConnectionWidget::pImpl
{
  ConnectionWidget* widget_;
  bool is_empty_;


  pImpl(ConnectionWidget* widget) : widget_(widget), is_empty_(true)
  {
  }


  void initializeForm(void)
  {
    widget_->device_combobox_->setSizeAdjustPolicy(QComboBox::AdjustToContents);

    connect(widget_->connect_button_, SIGNAL(clicked(bool)),
            widget_, SLOT(connectPressed(bool)));
    connect(widget_->rescan_button_, SIGNAL(clicked(bool)),
            widget_, SLOT(rescanPressed()));
  }
};


ConnectionWidget::ConnectionWidget(QWidget* widget)
  : QWidget(widget), pimpl(new pImpl(this))
{
  setupUi(this);
  pimpl->initializeForm();

  vector<string> empty_devices;
  setDevices(empty_devices);
}


ConnectionWidget::~ConnectionWidget(void)
{
}


void ConnectionWidget::connectPressed(bool checked)
{
  // 接続ボタンが押下されたとき、setConnected() が呼ばれるまでボタンを無効にする
  connect_button_->setEnabled(false);
  string device_name = device_combobox_->currentText().toStdString();
  string device = device_name.substr(0, device_name.find(' '));
  emit connectRequest(checked, device);
}


void ConnectionWidget::rescanPressed(void)
{
  emit rescanRequest();
}


void ConnectionWidget::setConnected(bool connected)
{
  connect_button_->setEnabled(true);
  connect_button_->setChecked(connected);

  if (connected) {
    connect_button_->setText(tr("Disconnect"));
  } else {
    connect_button_->setText(tr("Connect"));
  }
  device_combobox_->setEnabled(! connected);
  rescan_button_->setEnabled(! connected);

  connect_button_->setFocus();
}


bool ConnectionWidget::isConnected(void) const
{
  return (connect_button_->isEnabled() && connect_button_->isChecked())
    ? true : false;
}


void ConnectionWidget::setDevices(const vector<string>& devices)
{
  device_combobox_->clear();
  for (vector<string>::const_iterator it = devices.begin();
       it != devices.end(); ++it) {
    device_combobox_->addItem(it->c_str());
  }

  bool connectable = (device_combobox_->count() == 0) ? false : true;
  device_combobox_->setEnabled(connectable);
  connect_button_->setEnabled(connectable);

  pimpl->is_empty_ = devices.empty();
  if (pimpl->is_empty_) {
    device_combobox_->addItem(tr("-- press rescan --"));
  }
}


vector<string> ConnectionWidget::devices(void)
{
  vector<string> devices;

  if (! pimpl->is_empty_) {
    size_t n = device_combobox_->count();
    for (size_t i = 0; i < n; ++n) {
      devices.push_back(device_combobox_->itemText(n).toStdString());
    }
  }

  return devices;
}


void ConnectionWidget::setEnabled(bool enable)
{
  QWidget::setEnabled(enable);
}


void ConnectionWidget::setFocus(void)
{
  if (! connect_button_->isEnabled()) {
    rescan_button_->setFocus();
  } else {
    connect_button_->setFocus();
  }
}
