// File: host/src/MainWindow.cpp
#include "MainWindow.h"
#include <QGesture>
#include <QScroller>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
  settings = new QSettings("EISConfigurator", "Settings", this);
  loadSettings();

  serial = new QSerialPort(this);
  connect(serial, &QSerialPort::readyRead, this, &MainWindow::handleSerialData);
  connect(serial, &QSerialPort::errorOccurred, this, &MainWindow::onPortError);

  blinkTimer = new QTimer(this);
  blinkTimer->setInterval(500);
  connect(blinkTimer, &QTimer::timeout, this, &MainWindow::onBlinkTimer);

  setupUi(); // Defined in MainWindow_UI.cpp

  // Auto-refresh ports after startup
  QTimer::singleShot(1000, this, &MainWindow::refreshPorts);

  grabGesture(Qt::SwipeGesture);
}

MainWindow::~MainWindow() {
  if (serial->isOpen()) {
    serial->close();
  }
}

void MainWindow::loadSettings() {
  cellConstant = settings->value("cellConstant", 1.0).toDouble();
}

void MainWindow::saveSettings() {
  settings->setValue("cellConstant", cellConstant);
}

bool MainWindow::event(QEvent *event) {
  if (event->type() == QEvent::Gesture) {
    QGestureEvent *ge = static_cast<QGestureEvent *>(event);
    if (QGesture *swipe = ge->gesture(Qt::SwipeGesture)) {
      handleSwipe(static_cast<QSwipeGesture *>(swipe));
      return true;
    }
  }
  return QMainWindow::event(event);
}

void MainWindow::handleSwipe(QSwipeGesture *gesture) {
  if (gesture->state() == Qt::GestureFinished) {
    if (gesture->horizontalDirection() == QSwipeGesture::Left) {
      if (mainTabWidget->currentIndex() < mainTabWidget->count() - 1)
        mainTabWidget->setCurrentIndex(mainTabWidget->currentIndex() + 1);
    } else if (gesture->horizontalDirection() == QSwipeGesture::Right) {
      if (mainTabWidget->currentIndex() > 0)
        mainTabWidget->setCurrentIndex(mainTabWidget->currentIndex() - 1);
    }
  }
}