#include "locolorselector.h"
#include <QColorDialog>
#include <QLayout>
#include <QDebug>

LoColorSelector::LoColorSelector(QWidget *parent) : QPushButton(parent) {
    init();
}
LoColorSelector::LoColorSelector(const QString &text, const QColor &color, QWidget *parent) : QPushButton(parent) {
    setText(text);
    setColor(color);
    init();
}
void LoColorSelector::init() {
    connect(this, &QPushButton::clicked, this, [this]{
        QColorDialog colorDlg(this);
        colorDlg.setOption(QColorDialog::ShowAlphaChannel);
        colorDlg.setOption(QColorDialog::DontUseNativeDialog);
        auto color = this->color;
        color.setAlpha(255);
        colorDlg.setCurrentColor(color);

        auto btn = new QPushButton(tr("Transparent"));
        connect(btn, &QPushButton::clicked, &colorDlg, [&colorDlg] {
            colorDlg.setCurrentColor(QColor(0,0,0,0));
            colorDlg.accept();
        });
        static_cast<QBoxLayout *>(colorDlg.layout()->itemAt(0)->layout()->itemAt(0)->layout())->insertWidget(2, btn);

        if(colorDlg.exec() != QColorDialog::Accepted) return;
        color = colorDlg.selectedColor();
        if(! color.isValid()) return;
        setColor(color);
        emit sColorChanged(color);
    });
}

void LoColorSelector::setColor(const QColor &color) {
    this->color = color;
    setStyleSheet("LoColorSelector{background-color: "+color.name(QColor::HexArgb)+"; color: "+(color.alpha()>127 && color.value()<192 ? "#ffffff" : "#000000")+";}");
}