

#include "triggerwidget.h"
#include <QDebug>
#include <QMessageBox>
#include <eismultiplexer.h>

TriggerWidget::TriggerWidget(uint16_t deviceSerial, uint16_t triggerNumber,
                             std::shared_ptr<struct eismultiplexer> multiplexer,
                             QWidget *parent):
    QWidget(parent),
    deviceSerial(deviceSerial),
    triggerNumber(triggerNumber),
    multiplexer(multiplexer),
    inputCheckbox("Input"),
    levelCheckbox("Level"),
    devicelabel(QString::asprintf("Device %04u", deviceSerial)),
    triggerlabel(QString::asprintf("Trigger %u", triggerNumber))
{
    hlayout.addLayout(&labellayout);
    vlayout.addLayout(&hlayout);

    inputCheckbox.setChecked(true);
    levelCheckbox.setEnabled(false);

    labellayout.addWidget(&devicelabel);
    labellayout.addWidget(&triggerlabel);

    line.setFrameShape(QFrame::HLine);
    line.setFrameShadow(QFrame::Sunken);
    vlayout.addWidget(&line);

    hlayout.addStretch();
    hlayout.addWidget(&inputCheckbox);
    hlayout.addWidget(&levelCheckbox);

    connect(&inputCheckbox, &QCheckBox::toggled, this, &TriggerWidget::onInputToggled);
    connect(&levelCheckbox, &QCheckBox::toggled, this, &TriggerWidget::onLevelToggled);

    setFixedHeight(96);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    setLayout(&vlayout);

    // Initialize trigger state
    updateTriggerState();
}

TriggerWidget::~TriggerWidget()
{
}

uint16_t TriggerWidget::getDeviceSerial() const
{
    return deviceSerial;
}

uint16_t TriggerWidget::getTriggerNumber() const
{
    return triggerNumber;
}

void TriggerWidget::onInputToggled(bool checked)
{
    updateTriggerState();
}

void TriggerWidget::onLevelToggled(bool checked)
{
    updateTriggerState();
}

void TriggerWidget::updateTriggerState()
{
    trigger_state_t state;
    if(inputCheckbox.isChecked())
    {
        levelCheckbox.blockSignals(true);
        levelCheckbox.setChecked(false);
        levelCheckbox.setEnabled(false);
        levelCheckbox.blockSignals(false);
    }
    else
    {
        levelCheckbox.setEnabled(true);
        state = levelCheckbox.isChecked() ? TRIGGER_HIGH : TRIGGER_LOW;
    }

    if (eismultiplexer_set_trigger_state(multiplexer.get(), triggerNumber, state) < 0) {
        QMessageBox::warning(this, tr("Trigger Configuration Failed"),
                             tr("Failed to set trigger %1 on device %2").arg(triggerNumber).arg(deviceSerial));
        qWarning() << "Failed to set trigger" << triggerNumber << "on device" << deviceSerial;
    }
}

