#include <QDebug>
#include <QLabel>
#include <QVBoxLayout>

#include "DashSensorDevice.h"
#include "DashSensorMath.h"
#include "MathProvider.h"
#include "TDeviceManager.h"
#include "TenkiDashboard.h"
#include "usbtenki.h"

TenkiDashboard::TenkiDashboard() {

    mainLayout = new QVBoxLayout;
    setLayout(mainLayout);

    setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum);

    QWidget *sensorsWidget = new QWidget();
    sensorsLayout = new QVBoxLayout();
    sensorsWidget->setLayout(sensorsLayout);
    sensorsWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum);

    mainLayout->addWidget(sensorsWidget);

    // Math

    if (MathProvider::instance().getDeviceCount() > 0) {

        QWidget *mathWidget = new QWidget();
        QVBoxLayout *mathLayout = new QVBoxLayout();
        mathWidget->setLayout(mathLayout);

        DashSensor *ds = new DashSensorMath();
        mathLayout->addWidget(ds);

        mainLayout->addWidget(mathWidget);
    }

    mainLayout->addStretch();

    TDeviceManager *deviceManager = &(TDeviceManager::instance());
    connect(deviceManager, &TDeviceManager::deviceAdded, this, &TenkiDashboard::addDevice);
    connect(deviceManager, &TDeviceManager::deviceRemoved, this, &TenkiDashboard::removeDevice);
}

TenkiDashboard::~TenkiDashboard() {
    // Lives forever
}

void TenkiDashboard::addDevice(const TDevice *device) {
    if (device->isSpecial()) {
        return;
    }

#ifdef Q_OS_LINUX
    if (!dxc320WarningShown && g_has_at_least_one_unseen_dxc320) {
        dxc320WarningShown = true;
        {
            QLabel *warning = new QLabel(
                "<b>Warning: A DXC320 was detected but is not visible.</b><br>"
                "&nbsp;&nbsp;&nbsp;&nbsp;• An active serial port connection may be interfering.<br>"
                "&nbsp;&nbsp;&nbsp;&nbsp;• Close the serial connection and restart the application.");
            warning->setTextFormat(Qt::RichText);
            warning->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);
            warning->setStyleSheet(
                "color: #7a3b00;"
                "background-color: #ffe0a0;"
                "border: 1px solid #c87000;"
                "border-radius: 4px;"
                "padding: 4px;");
            mainLayout->insertWidget(0, warning);
        }
    }
#endif

    DashSensor *ds = sensors.value(device->serialNumber);

    if (!ds) {
        ds = new DashSensorDevice(device);
        sensors.insert(device->serialNumber, ds);
    }

    ds->activate();

    sensorsLayout->addWidget(ds);
    ds->setVisible(true);
}

void TenkiDashboard::removeDevice(const TDevice *device) {

    DashSensor *ds = sensors.value(device->serialNumber);

    if (ds) {
        ds->deactivate();
        ds->setVisible(false);
        sensorsLayout->removeWidget(ds);
    }
}
