#include "universeview.h"
#include "ui_universeview.h"

#include <QComboBox>
#include <QLabel>
#include <QMetaEnum>

/**
 * @brief UniverseView::UniverseView
 * @param parent
 */
UniverseView::UniverseView(QWidget *parent, QSacnUniverse *universe)
  : QMainWindow(parent)
  , ui(new Ui::UniverseView())
{
  ui->setupUi(this);

  auto model = new UniverseModel(this);
  ui->tableView->setModel(model);

  model->setUniverse(universe);

  // update the status bar whenever the universe refreshes
  connect(model, &UniverseModel::recievedUpdate,
          this, &UniverseView::updateStatus);

  // add data format combobox to toolbar
  auto formatLabel = new QLabel(this);
  formatLabel->setText(tr("Data Format") + ": ");
  ui->toolBar->addWidget(formatLabel);
  auto dataModes = new QComboBox(this);
  const QMetaEnum types = QMetaEnum::fromType<UniverseModel::data_modes>();
  for (int i=0; i < types.keyCount(); ++i)
    dataModes->addItem(types.key(i));
  connect(dataModes, &QComboBox::currentTextChanged,
          model, &UniverseModel::setDataMode);
  ui->toolBar->addWidget(dataModes);

  ui->toolBar->addSeparator();

  // add priority picker to the toolbar
  auto priorityLabel = new QLabel(this);
  priorityLabel->setText(tr("Priority") + ": ");
  ui->toolBar->addWidget(priorityLabel);
  prioritySpinBox = new QSpinBox(this);
  prioritySpinBox->setMinimum(0);
  prioritySpinBox->setValue(100);
  prioritySpinBox->setMaximum(200);
  prioritySpinBox->setEnabled(false);
  ui->toolBar->addWidget(prioritySpinBox);

  ui->toolBar->addSeparator();

  updateStatus(universe);
  if (universe->isEditable())
    {
      prioritySpinBox->setValue(universe->priority());
      prioritySpinBox->setEnabled(true);
      connect(prioritySpinBox, &QSpinBox::valueChanged,
              universe, &QSacnUniverse::setPriority);
    }
}


/**
 * @brief UniverseView::~UniverseView
 */
UniverseView::~UniverseView()
{
    delete ui;
}


/**
 * @brief UniverseView::updateStatusBar
 * @param universe
 */
void UniverseView::updateStatus(QSacnUniverse* universe)
{
  // window title
  QString titlestring = QString("%1 " + tr("Universe") + " %2 - \"%3\"").arg(
        universe->isEditable() ? tr("Editing") : tr("Viewing"),
        QString::number(universe->number()),
        universe->description());
  this->setWindowTitle(titlestring);

  if (!universe->isEditable())
    {
      // status bar
      ui->statusbar->clearMessage();
      QString message = QString("%1 " + tr("Hz")).arg(
            QString::number(universe->rxRate()));
      ui->statusbar->showMessage(message, 2500);

      // priority spinbox
      prioritySpinBox->setValue(universe->priority());
    }
}
