#include <QSettings>
#include <QVBoxLayout>

#include "BigView.h"
#include "TDeviceManager.h"

BigView::BigView() { setLayout(new QVBoxLayout()); }

BigView::~BigView(void) {
    // Singleton always exists
}

void BigView::refreshDevice(const TDevice *device) {

    const QVector<TChannel *> &channels = device->channels;

    for (int i = 0; i < channels.size(); i++) {
        TChannel *channel = channels[i];
        BigLabel *label = labelByChannel.value(channel->id);
        if (label) {
            label->refresh(channel);
        }
    }
}

void BigView::addChannel(const QString &id) {

    BigLabel *label = labelByChannel.value(id);
    if (label) {
        return;
    }

    TChannel *channel = TDeviceManager::instance().getChannel(id);
    if (!channel) {
        return;
    }

    TDevice *device = channel->device;
    subscribe(device);

    label = new BigLabel();
    labelByChannel.insert(id, label);
    label->refresh(channel);

    layout()->addWidget(label);
}

void BigView::removeChannel(const QString &id) {

    BigLabel *label = labelByChannel.value(id);
    if (!label) {
        return;
    }

    labelByChannel.remove(id);

    label->setVisible(false);
    layout()->removeWidget(label);
    delete label;

    TChannel *channel = TDeviceManager::instance().getChannel(id);
    if (!channel) {
        return;
    }

    TDevice *device = channel->device;

    for (const QString &remainingId : labelByChannel.keys()) {
        TChannel *remaining = TDeviceManager::instance().getChannel(remainingId);
        if (remaining && remaining->device == device) {
            return;
        }
    }

    unsubscribe(device);
}

void BigView::subscribe(const TDevice *device) {

    TDeviceManager &deviceManager = TDeviceManager::instance();
    TDeviceSignal *signal = deviceManager.getDeviceSignal(device->serialNumber);

    if (!signal) {
        return;
    }

    connect(signal, &TDeviceSignal::deviceConnected, this, &BigView::refreshDevice, Qt::UniqueConnection);
    connect(signal, &TDeviceSignal::deviceDisconnected, this, &BigView::refreshDevice, Qt::UniqueConnection);
    connect(signal, &TDeviceSignal::deviceUpdated, this, &BigView::refreshDevice, Qt::UniqueConnection);
}

void BigView::unsubscribe(const TDevice *device) {

    TDeviceManager &deviceManager = TDeviceManager::instance();
    TDeviceSignal *signal = deviceManager.getDeviceSignal(device->serialNumber);

    if (!signal) {
        return;
    }

    signal->disconnect(this);
}
