#include "stretchpanel.h"
#include <QVBoxLayout>
#include <QDebug>
#include <QToolButton>
#include "imageringlist.h"

const float BLACK_POINT_SIGMA = -2.8f;
const float MAD_TO_SIGMA = 1.4826f;
const float TARGET_BACKGROUND = 0.25f;

float MTF(float x, float m)
{
    if(x < 0)return 0;
    if(x > 1)return 1;
    return ((m - 1) * x) / ((2 * m - 1) * x - m);
}

StretchPanel::StretchPanel(QWidget *parent) : QWidget(parent)
{
    QHBoxLayout *layout = new QHBoxLayout(this);
    setLayout(layout);

    m_stfSlider = new STFSlider(this);
    layout->addWidget(m_stfSlider);
    connect(m_stfSlider, SIGNAL(paramChanged(float, float, float)), this, SIGNAL(paramChanged(float,float,float)));

    QToolButton *autoStretchButton = new QToolButton(this);
    autoStretchButton->setIcon(QIcon(":/nuke.png"));
    autoStretchButton->setToolTip(tr("Auto Stretch F12"));
    autoStretchButton->setShortcut(Qt::Key_F12);
    connect(autoStretchButton, SIGNAL(pressed()), this, SIGNAL(autoStretch()));

    QToolButton *resetButton = new QToolButton(this);
    resetButton->setIcon(style()->standardIcon(QStyle::SP_DialogResetButton));
    resetButton->setToolTip(tr("Reset Screen Transfer Function F11"));
    resetButton->setShortcut(Qt::Key_F11);
    connect(resetButton, &QToolButton::pressed, this, &StretchPanel::resetMTF);

    QToolButton *invertButton = new QToolButton(this);
    invertButton->setIcon(QIcon(":/invert.png"));
    invertButton->setCheckable(true);
    connect(invertButton, SIGNAL(toggled(bool)), this, SIGNAL(invert(bool)));

    QToolButton *superPixelButton = new QToolButton(this);
    superPixelButton->setIcon(QIcon(":/bayer.png"));
    superPixelButton->setCheckable(true);
    superPixelButton->setToolTip(tr("Superpixel CFA draw 2x2 pixel as one"));
    connect(superPixelButton, SIGNAL(toggled(bool)), this, SIGNAL(superPixel(bool)));

    layout->addWidget(autoStretchButton);
    layout->addWidget(resetButton);
    layout->addWidget(invertButton);
    layout->addWidget(superPixelButton);
}

void StretchPanel::stretchImage(Image *img)
{
    if(img)
    {
        if(img->rawImage())
        {
            double median, mad;
            img->rawImage()->imageStats(nullptr, nullptr, &median, nullptr, nullptr, &mad);
            median /= img->rawImage()->norm();
            mad /= img->rawImage()->norm();
            float bp = median + mad * BLACK_POINT_SIGMA * MAD_TO_SIGMA;
            float mid = MTF(median - bp, TARGET_BACKGROUND);
            m_stfSlider->setMTFParams(bp, mid, 1.0f);
            emit paramChanged(m_stfSlider->blackPoint(), m_stfSlider->midPoint(), 1.0f);
        }
    }
}

void StretchPanel::resetMTF()
{
    m_stfSlider->setMTFParams(0, 0.5, 1);
    emit paramChanged(0, 0.5, 1);
}

