#include <QDebug>
#include <QHBoxLayout>
#include <QLabel>
#include <QSettings>

#include "DataSourceCheckBox.h"
#include "TDeviceManager.h"

DataSourceCheckBox::DataSourceCheckBox(const TChannel *channel) : channelID(channel->id) {
    QSettings settings;

    QString caption = channelID + "  --  " + channel->description;

    checkbox = new QCheckBox();
    checkbox->setText(caption);

    checkbox->setChecked(settings.value("sourcesChecked/" + channelID).toBool());

    QString alias = TDeviceManager::instance().getAlias(channelID);
    lbl_alias = new QLabel();
    refreshAlias(channelID, alias);

    QHBoxLayout *lay = new QHBoxLayout();
    lay->setContentsMargins(0, 0, 0, 0);
    setLayout(lay);
    lay->addWidget(checkbox);
    lay->addWidget(lbl_alias);
    lay->addStretch();

    connect(checkbox, SIGNAL(stateChanged(int)), this, SLOT(checkChanged(int)));
    connect(&(TDeviceManager::instance()), &TDeviceManager::channelAliasUpdated, this,
            &DataSourceCheckBox::refreshAlias);
}

DataSourceCheckBox::~DataSourceCheckBox() {}

const QString &DataSourceCheckBox::getChannelId() const { return channelID; }

bool DataSourceCheckBox::isChecked() const { return checkbox->isChecked(); }

void DataSourceCheckBox::refreshAlias(const QString id, const QString alias) {
    if (id == channelID) {
        if (alias.length() > 0) {
            lbl_alias->setText("(" + alias + ")");
        } else {
            lbl_alias->setText("");
        }
    }
}

void DataSourceCheckBox::checkChanged(int st) {
    QSettings settings;
    settings.setValue("sourcesChecked/" + channelID, checkbox->isChecked());
    (void)st;
}

void DataSourceCheckBox::setChecked(bool checked) { checkbox->setChecked(checked); }
