#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->color, this);
        colorDlg.setOption(QColorDialog::ShowAlphaChannel);
        colorDlg.setOption(QColorDialog::DontUseNativeDialog);

        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;
        QColor color = colorDlg.selectedColor();
        if(color == this->color) return;
        if(! color.isValid()) return;
        if(color.alpha()==0 && this->color.alpha()==0) color.setAlpha(255);
        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")+";}");
}
