#include "audio_widget.h"
#include <QLayout>
#include <qglobal.h>

AudioWidget::AudioWidget(QWidget* parent)
    : QWidget(parent)
{
    _CreateUi();
    _CreateConnect();
    _mutebox->setChecked(true);

    // setMinimumHeight(10);
    // setMaximumHeight(24);
}

void AudioWidget::_CreateUi()
{
    // auto hLayout = new QHBoxLayout;
    // hLayout->setContentsMargins(0, 0, 0, 0);
    // hLayout->setSpacing(2);

    // _nameLabel = new QLabel;
    // QFont smallFont = _nameLabel->font();
    // smallFont.setPointSize(smallFont.pointSize() - 1);
    // _nameLabel->setFont(smallFont);

    // _mutebox = new QCheckBox("静音");
    // _mutebox->setFont(smallFont);

    // _render = new AudioRender;
    // _render->setMaximumHeight(14); // 更小的高度

    // _volumeBox = new QDoubleSpinBox;
    // _volumeBox->setMinimum(0);
    // _volumeBox->setValue(1);
    // _volumeBox->setFont(smallFont);
    // _volumeBox->setFixedHeight(18);

    // hLayout->addWidget(_nameLabel);
    // hLayout->addWidget(_mutebox);

    // auto scaleLayout = new QHBoxLayout;
    // scaleLayout->setContentsMargins(0, 0, 0, 0);
    // scaleLayout->setSpacing(2);
    // QLabel* scaleLabel = new QLabel("调幅:");
    // scaleLabel->setFont(smallFont);
    // scaleLayout->addWidget(scaleLabel);
    // scaleLayout->addWidget(_volumeBox);
    // hLayout->addLayout(scaleLayout);

    // auto vLayout = new QVBoxLayout;
    // vLayout->setContentsMargins(0, 0, 0, 0);
    // vLayout->setSpacing(2);
    // vLayout->addLayout(hLayout);
    // vLayout->addWidget(_render);
    // setLayout(vLayout);
    // setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);

    auto hLayout = new QHBoxLayout;
    hLayout->setContentsMargins(0, 0, 0, 0);
    hLayout->setSpacing(6);

    _nameLabel = new QLabel;
    _render = new AudioRender;
    _render->setMaximumHeight(14);
    _render->setMinimumWidth(60);
    _render->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    _mutebox = new QCheckBox("静音");
    _volumeBox = new QDoubleSpinBox;
    _volumeBox->setMinimum(0);
    _volumeBox->setValue(1);
    _volumeBox->setFixedHeight(18);
    _volumeBox->setMaximumWidth(48);

    QLabel* scaleLabel = new QLabel("调幅:");

    hLayout->addWidget(_nameLabel);
    hLayout->addWidget(_render, 1); // 音量条居中拉伸
    hLayout->addWidget(_mutebox);
    hLayout->addWidget(scaleLabel);
    hLayout->addWidget(_volumeBox);

    setLayout(hLayout);
    setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);
}

void AudioWidget::_CreateConnect()
{
    connect(_mutebox, &QCheckBox::stateChanged, this, [this](int) {
        if (_mutebox->isChecked()) {
            emit SetVolumeScale(0);
            _volumeBox->setEnabled(false);
        } else {
            _volumeBox->setEnabled(true);
            emit SetVolumeScale(_volumeBox->value());
        }
    });

    connect(_volumeBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, [this] {
        emit SetVolumeScale(_volumeBox->value());
    });
}
