#include "X502DoutPinStatesDialog.h"
#include "ui_X502DoutPinStatesDialog.h"
#include "QLedIndicator.h"

X502DoutPinStatesDialog::X502DoutPinStatesDialog(QWidget *parent, unsigned value, int ch_cnt) :
    QDialog(parent),
    ui(new Ui::X502DoutPinStatesDialog), m_async_dout_update(false) {
    ui->setupUi(this);

    for (int i = 0; i < ch_cnt; i++) {
        int pin_num = ch_cnt - i - 1;
        addDoutPin(pin_num, QString("DO%1").arg(QString::number(pin_num+1)));
    }
    connect(ui->doutAsyncHexVal, SIGNAL(editingFinished()), this, SLOT(onAsyncDoutHexChanged()));
    updateOutIndicators(value);
}

X502DoutPinStatesDialog::~X502DoutPinStatesDialog() {
    delete ui;
}

unsigned X502DoutPinStatesDialog::currentValue() const {
    return ui->doutAsyncHexVal->value();
}

void X502DoutPinStatesDialog::updateOutIndicators(unsigned value) {
    m_async_dout_update = true;
    for (int i = 0; i < m_asyncDoutStates.size(); i++) {
        m_asyncDoutStates.at(i).led->setChecked(value & (1 << m_asyncDoutStates.at(i).pin_num));
    }

    ui->doutAsyncHexVal->setValue(value);
    m_async_dout_update = false;
}

void X502DoutPinStatesDialog::onAsyncDoutPinChanged() {
    if (!m_async_dout_update) {
        unsigned out_val = 0;
        for (int i = 0; i < m_asyncDoutStates.size(); i++) {
            if (m_asyncDoutStates.at(i).led->isChecked()) {
                out_val |= (1 << m_asyncDoutStates.at(i).pin_num);
            }
        }
        updateOutIndicators(out_val);
    }
}

void X502DoutPinStatesDialog::onAsyncDoutHexChanged() {
    if (!m_async_dout_update) {
        updateOutIndicators(ui->doutAsyncHexVal->value());
    }
}

void X502DoutPinStatesDialog::addDoutPin(int pin_num, QString name) {
    QLedIndicator *ind = new QLedIndicator();
    AsyncPinState state(pin_num, ind);
    int col = ui->asyncOutGrid->columnCount();
    ui->asyncOutGrid->addWidget(new QLabel(name), 0, col, 1, 1, Qt::AlignHCenter);
    ui->asyncOutGrid->addWidget(ind, 1, col);
    connect(ind, SIGNAL(toggled(bool)), SLOT(onAsyncDoutPinChanged()));
    m_asyncDoutStates.append(state);
}
