#include "plugingenericgui.h"
#include "logcategories.h"

pluginGenericGUI::pluginGenericGUI(QWidget *parent) : QWidget(parent)
{
    layout = new QGridLayout();
    bypassChk = new QCheckBox("Bypass");

    setWindowTitle("Generic plugin window");
    row=0;
    col=0;
    layout->addWidget(bypassChk, row, col);
    row++;
    //col++;

    connect(bypassChk, &QCheckBox::stateChanged,
            [=](const int &value) {
                emit setBypass((bool)value);
            });

}

pluginGenericGUI::~pluginGenericGUI()
{
    delete layout;
}


void pluginGenericGUI::definePlugin()
{
    // TODO: make a plugin struct with plugin title and other information
    QString name = QString("Plugin Name");
    setWindowTitle(name);
}

void pluginGenericGUI::addControl(controlsType control)
{
    (void)control;
}

void pluginGenericGUI::addControls(QVector<controlsType> controls)
{
    // it is really a lot better if we clear out the vectors safely first.

    this->controls = controls;

    for(int i=0; i < controls.size(); i++)
    {
        controlsType c = controls.at(i);
        QSlider *s = new QSlider();
        QLabel *l = new QLabel();
        s->setMinimum(0);
        s->setMaximum(255);
        s->setPageStep(1);
        s->setValue(c.value);
        s->setToolTip(c.label);
        l->setText(c.label);
        sliders.push_back(s);
        labels.push_back(l);
    }
    showControls();
    makeConnections();
}

void pluginGenericGUI::showControls()
{

    for(int i=0; i < sliders.size(); i++)
    {
       layout->addWidget(sliders.at(i), row, col);
       layout->addWidget(labels.at(i), row+1, col+0);
       col++;
    }

    setLayout(layout);
    setWindowTitle(QString("Plugin controls for 0x%1").arg(controls.at(0).instanceId, 16, 16, QChar('0')));
}

void pluginGenericGUI::makeConnections()
{

    for(int i=0; i < sliders.length(); i++)
    {
        connect(
            sliders.at(i),
            &QSlider::valueChanged,
            [=](const int &newValue) {
                controlsType c = controls.at(i);
                c.value = convertLevel(newValue, c.min, c.max);
                qDebug() << __PRETTY_FUNCTION__ << "Setting control to: " << c.value;
                emit setControl(c);
            });
    }
}

float pluginGenericGUI::convertLevel(int level, float min, float max)
{

    float span = max - min;
    float stepSize = span / 255.0f;
    float amplitude = level * stepSize;
    float absLevel = amplitude + min;

    return absLevel;
}







