/*!
  \file
  \brief URG ポートの表示

  \author Satofumi KAMIMURA

  $Id: UrgPortsWidget.cpp 1439 2009-10-22 02:09:34Z satofumi $
*/

#include "UrgPortsWidget.h"
#include "UrgUsbCom.h"
#include "FindComPorts.h"
#include <QShortcut>

using namespace qrk;
using namespace std;


struct UrgPortsWidget::pImpl
{
  void initializeForm(UrgPortsWidget* parent)
  {
    // シグナルの接続
    connect(parent->rescan_button_, SIGNAL(clicked()),
            parent, SLOT(rescanHandler()));
  }


  void rescanPorts(UrgPortsWidget* parent)
  {
    FindComPorts urg_finder;
    urg_finder.addBaseName("/dev/ttyACM");
    urg_finder.addBaseName("/dev/tty.usbmodem");
    urg_finder.addDriverName("URG Series USB Device Driver");
    urg_finder.addDriverName("URG-X002 USB Device Driver");

    vector<string> urg_ports;
    urg_finder.find(urg_ports);

    parent->ports_list_widget_->clear();

    UrgUsbCom urg_usb;
    for (vector<string>::iterator it = urg_ports.begin();
         it != urg_ports.end(); ++it) {
      string name = *it
        + (urg_usb.isUsbCom(it->c_str()) ? " [URG]" : "");

      parent->ports_list_widget_->addItem(name.c_str());
    }
  }
};


UrgPortsWidget::UrgPortsWidget(QWidget* parent)
  : QWidget(parent), pimpl(new pImpl)
{
  setupUi(this);

  // フォームを初期化し、最初の表示を行う
  pimpl->initializeForm(this);
  pimpl->rescanPorts(this);

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


UrgPortsWidget::~UrgPortsWidget(void)
{
}


void UrgPortsWidget::rescanHandler(void)
{
  pimpl->rescanPorts(this);
}
