#include "gpssystemdialog.hh"
#include "settings.hh"


GPSSystemDialog::GPSSystemDialog(Config *config, QWidget *parent)
  : QDialog(parent), _config(config), _myGPSSystem(new GPSSystem(this)), _gpsSystem(nullptr)
{
  setWindowTitle(tr("Create DMR APRS Sysmtem"));
  construct();
}

GPSSystemDialog::GPSSystemDialog(Config *config, GPSSystem *gps, QWidget *parent)
  : QDialog(parent), _config(config), _myGPSSystem(new GPSSystem(this)), _gpsSystem(gps)
{
  setWindowTitle(tr("Edit DMR APRS Sysmtem"));
  if (_gpsSystem)
    _myGPSSystem->copy(*_gpsSystem);
  construct();
}

void
GPSSystemDialog::construct() {
  setupUi(this);
  Settings settings;

  // setup name entry
  name->setText(_myGPSSystem->name());

  // setup contact entry
  for (int i=0; i<_config->contacts()->digitalCount(); i++) {
    destination->addItem(_config->contacts()->digitalContact(i)->name(),
                         QVariant::fromValue(_config->contacts()->digitalContact(i)));
    if (_myGPSSystem->contactObj() == _config->contacts()->digitalContact(i))
      destination->setCurrentIndex(i);
  }

  // setup period
  period->setValue(_myGPSSystem->period());

  // setup revert channel
  revChannel->addItem(tr("[Selected]"), QVariant::fromValue<DMRChannel *>(nullptr));
  if (! _myGPSSystem->hasRevertChannel())
    revChannel->setCurrentIndex(0);
  for (int i=1,j=0; j<_config->channelList()->count(); j++) {
    if (! _config->channelList()->channel(j)->is<DMRChannel>())
      continue;
    revChannel->addItem(_config->channelList()->channel(j)->name(),
                        QVariant::fromValue(_config->channelList()->channel(j)->as<DMRChannel>()));
    if (_myGPSSystem->hasRevertChannel() &&
        (_myGPSSystem->revertChannel() == _config->channelList()->channel(j)->as<DMRChannel>()))
      revChannel->setCurrentIndex(i);
    i++;
  }

  extensionView->setObjectName("dmrAPRSSystemExtension");
  extensionView->setObject(_myGPSSystem, _config);
  if (! settings.showExtensions())
    return tabWidget->tabBar()->hide();
}

GPSSystem *
GPSSystemDialog::gpsSystem() {
  _myGPSSystem->setName(name->text().simplified());
  _myGPSSystem->setContactObj(destination->currentData().value<DMRContact*>());
  _myGPSSystem->setPeriod(period->value());
  if (revChannel->currentData().isNull())
    _myGPSSystem->resetRevertChannel();
  else
    _myGPSSystem->setRevertChannel(revChannel->currentData().value<DMRChannel*>());

  GPSSystem *sys = _myGPSSystem;
  if (_gpsSystem) {
    _gpsSystem->copy(*_myGPSSystem);
    sys = _gpsSystem;
  } else {
    _myGPSSystem->setParent(nullptr);
  }

  return sys;
}
