#include <graph/server/gui/specdialog/specdialog.h>
#include <graph/server/spec.h>
#include <graph/server/ui_specdialog.h>

namespace Graph::GUI {
SpecDialog* SpecDialog::instance = nullptr;

SpecDialog* SpecDialog::getInstance() {
  if (!instance)
    instance = new SpecDialog();

  return instance;
}

void SpecDialog::close() {
  if (instance)
    delete instance;
}

SpecDialog::SpecDialog(QWidget* parent) : QDialog(parent), ui(new Ui::SpecDialog) {
  ui->setupUi(this);

  series = new QStringListModel(this);
  ui->seriesListView->setModel(series);

  ui->seriesListView->setEditTriggers(QAbstractItemView::AnyKeyPressed | QAbstractItemView::DoubleClicked);

  connect(ui->addSeriesButton, &QPushButton::clicked, [&]() {
    int row = series->rowCount();
    series->insertRow(row);
    QModelIndex index = series->index(row);
    ui->seriesListView->setCurrentIndex(index);
    ui->seriesListView->edit(index);
  });

  connect(ui->removeSeriesButton, &QPushButton::clicked, [&]() { series->removeRow(ui->seriesListView->currentIndex().row()); });
}

SpecDialog::~SpecDialog() {
  delete series;
}

chart_spec_t SpecDialog::getSpec() const {
  return {.title = ui->chartTitle->text(),
          .grid = ui->grid->isChecked(),
          .legend = ui->legend->isChecked(),
          .keep_all = ui->keepAll->isChecked(),
          .keep_limit = static_cast<unsigned long>(ui->keep->value()),
          .decimate = ui->decimate->value(),
          .axis = {.x = {.label = ui->xTitle->text(), .auto_limit = ui->xAutoRange->isChecked(), .min = ui->xMin->value(), .max = ui->xMax->value()},
                   .y = {.label = ui->yTitle->text(), .auto_limit = ui->yAutoRange->isChecked(), .min = ui->yMin->value(), .max = ui->yMax->value()}},
          .series = series->stringList()};
}
} // namespace Graph::GUI