#include "audio_render.h"

#include <QPainter>

AudioRender::AudioRender(QLabel* parent)
    : QLabel(parent)
{}
void AudioRender::setLevel(float volume)
{
    float val = 0;
    if (volume < 0) {
        volume = -volume;
    }

    if (volume > 0.001) {
        val = (20.0f * log10(volume) + 60.0f) / 60.0f;
    }

    float diff = val - _lastShowVal;
    if (diff < -0.015f) {
        diff = -0.015f;
    }
    _lastShowVal += diff;
}

void AudioRender::paintEvent(QPaintEvent* event)
{
    int val = _lastShowVal * width();
    QPainter painter(this);
    QPen pen(Qt::green, height());
    painter.setPen(pen);
    painter.drawLine(0, 0, val, 0);
    pen.setColor(Qt::gray);
    painter.setPen(pen);
    painter.drawLine(val, 0, width(), 0);
}

RenderArea::RenderArea(QWidget* parent)
    : QLabel(parent)
{
    setBackgroundRole(QPalette::Base);
    setAutoFillBackground(true);

    // setMinimumHeight(10);
    // setMaximumHeight(30);
    // setMinimumWidth(100);
    // setMaximumWidth(200);
}

void RenderArea::paintEvent(QPaintEvent* /* event */)
{
    QPainter painter(this);

    painter.setPen(Qt::black);
    painter.drawRect(QRect(painter.viewport().left() + 10,
                           painter.viewport().top() + 10,
                           painter.viewport().right() - 20,
                           painter.viewport().bottom() - 20));
    if (m_level == 0.0)
        return;

    int pos = ((painter.viewport().right() - 20) - (painter.viewport().left() + 11)) * m_level;
    painter.fillRect(painter.viewport().left() + 11,
                     painter.viewport().top() + 10,
                     pos,
                     painter.viewport().height() - 21,
                     Qt::red);
}

void RenderArea::setLevel(qreal value)
{
    m_level = value;
    update();
}
