/*
 * Copyright (C) 2023, KylinSoft Co., Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
**/
#include "wallpaperui.h"
#include "ukcccommon.h"
using namespace ukcc;

WallpaperUi::WallpaperUi()
{
    setAttribute(Qt::WA_DeleteOnClose);
    uiLayout = new QVBoxLayout(this);
    uiLayout->setMargin(0);
    uiLayout->setSpacing(8);
    createObject();
    initUi();
    initColors();
    initSignals();
}

WallpaperUi::~WallpaperUi()
{

}

void WallpaperUi::createObject()
{
    wallpaperTitleLabel = new TitleLabel(this);
    previewLabel        = new PreviewLabel(this);
    settingGroup        = new SettingGroup(this);
    modeWidget          = new ComboxWidget(tr("Background"), settingGroup);
    typeWidget          = new ComboxWidget(tr("Type"), settingGroup);
    colorGroup          = new SettingGroup(settingGroup);
    addbuttonFrame      = new UkccFrame(colorGroup);
    addbuttonlayout     = new QHBoxLayout(addbuttonFrame);
    colorAddButton      = new AddButton(addbuttonFrame);
    colorFrame          = new UkccFrame(colorGroup);
    colorLayout         = new FlowLayout(colorFrame, 16, -1, -1);
    picBtnFrame         = new UkccFrame(settingGroup);
    picFrame            = new UkccFrame(picBtnFrame);
    pictureLayout       = new FlowLayout(picFrame, 16, -1, -1);
    bottomFrame         = new UkccFrame(picBtnFrame);
}

void WallpaperUi::initUi()
{
    UkccFrame   *previewFrame  = new UkccFrame(this);
    QHBoxLayout *previewLayout = new QHBoxLayout(previewFrame);

    uiLayout->addWidget(wallpaperTitleLabel);
    uiLayout->addWidget(previewFrame);
    uiLayout->addWidget(settingGroup);
    uiLayout->addStretch();

    addbuttonlayout  -> setMargin(0);
    modeWidget       -> setTitleFixedWidth(172);
    typeWidget       -> setTitleFixedWidth(172);
    settingGroup     -> addWidget(modeWidget);
    settingGroup     -> addWidget(typeWidget);
    settingGroup     -> addWidget(colorGroup);
    settingGroup     -> addWidget(picBtnFrame);
    colorGroup       -> addWidget(colorFrame);
    colorGroup       -> addWidget(addbuttonFrame);
    addbuttonlayout  -> addWidget(colorAddButton);
    picFrame         -> setLineWidth(0);

    wallpaperTitleLabel->setText(tr("Desktop Background"));

    previewFrame->setFixedHeight(212);
    previewLayout->addWidget(previewLabel);
    previewLayout->addStretch();
    previewLayout->setSpacing(8);
    previewLabel->setFixedSize(300, 180);
    previewLayout->addStretch();

    QVBoxLayout *picBtnLayout = new QVBoxLayout(picBtnFrame);
    picBtnLayout->setMargin(0);
    picBtnLayout->setSpacing(0);
    picBtnLayout->addWidget(picFrame);
    picBtnLayout->addWidget(bottomFrame);

    QHBoxLayout *bottomLayout = new QHBoxLayout(bottomFrame);
    bottomLayout->setSpacing(32);
    bottomLayout->setContentsMargins(16, 0, 16, 16);
    localBtn  = new QPushButton(bottomFrame);
    onlineBtn = new QPushButton(bottomFrame);
    resetBtn  = new QPushButton(bottomFrame);
    bottomLayout->addWidget(localBtn);
    bottomLayout->addWidget(onlineBtn);
    bottomLayout->addStretch();
    bottomLayout->addWidget(resetBtn);

    //~ contents_path /Wallpaper/Local Pictures
    localBtn->setText(tr("Local Pictures"));
    //~ contents_path /Wallpaper/Online Pictures
    onlineBtn->setText(tr("Online Pictures"));
    //~ contents_path /Wallpaper/Reset To Default
    resetBtn->setText(tr("Reset To Default"));
    onlineBtn->setFocusPolicy(Qt::NoFocus);
    onlineBtn->setContentsMargins(0, 0, 0, 0);
    onlineBtn->setCursor(QCursor(Qt::PointingHandCursor));
    onlineBtn->setStyleSheet("QPushButton{background: transparent;border-radius: 4px;text-decoration: underline;}");

    connect(modeWidget->comboBox(), QOverload<const QString&>::of(&QComboBox::activated), this, [=](const QString &mode){
        if (modeWidget->comboBox()->currentData().toString() == "picture") {
            showPictures();
            UkccCommon::buriedSettings("Wallpaper", QString("Background"), QString("select"), "picture");
        } else {
            showColors();
            UkccCommon::buriedSettings("Wallpaper", QString("Background"), QString("select"), "color");
        }
    });
}

void WallpaperUi::initColors()
{
    QStringList colors;
    colors << "#2d7d9a" << "#018574" << "#107c10" << "#10893e" << "#038387" << "#486860" << "#525e54" << "#7e735f" << "#4c4a48" << "#000000";
    colors << "#ff8c00" << "#e81123" << "#d13438" << "#c30052" << "#bf0077" << "#9a0089" << "#881798" << "#744da9" << "#8764b8" << "#e9e9e9";

    for (QString color : colors){
        QPushButton *button = new QPushButton(colorFrame);
        button->setFixedSize(QSize(48, 48));
        QString btnQss = QString("QPushButton{background: %1; border: none; border-radius: 4px;}").arg(color);
        button->setStyleSheet(btnQss);

        connect(button, &QPushButton::clicked, [=](){
            previewLabel->setColor(color);
            previewLabel->update();
            Q_EMIT wallpaperChanged(modeWidget->comboBox()->currentData().toString(), color);
        });
        colorLayout->addWidget(button);
    }
}

void WallpaperUi::initSignals()
{
    connect(typeWidget->comboBox(), QOverload<const QString&>::of(&QComboBox::activated), this, [=](const QString &type){
        previewLabel->setMode(typeWidget->comboBox()->currentData().toString());
        previewLabel->update();
        Q_EMIT typeChanged(typeWidget->comboBox()->currentData().toString());
    });
    connect(localBtn, &QPushButton::clicked, this, [=](){
        Q_EMIT localButtonClicked();
    });
    connect(onlineBtn, &QPushButton::clicked, this, [=](){
        Q_EMIT onlineButtonClicked();
    });
    connect(resetBtn, &QPushButton::clicked, this, [=](){
        Q_EMIT resetButtonClicked();
    });
    connect(colorAddButton, &AddButton::clicked, this, [=](){
        ColorDialog *colordialog = new ColorDialog(this);
        colordialog->setAttribute(Qt::WA_DeleteOnClose);
        connect(colordialog, &ColorDialog::colorSelected, this, [=](QColor color){
            previewLabel->setColor(color.name());
            previewLabel->update();
            Q_EMIT wallpaperChanged(modeWidget->comboBox()->currentData().toString(), color.name());
        });
        colordialog->exec();
    });

}

void WallpaperUi::setWallpaperModes(const QStringList &modeList, const QStringList &modeDataList)
{
    if (modeList.size() != modeDataList.size()) {
        qWarning()<<"modeList.size():"<<modeList.size()<<" != modeDataList.size():"<<modeDataList.size();
        return;
    }
    modeWidget->comboBox()->clear();
    for (int i = 0; i < modeList.size(); ++i) {
        modeWidget->comboBox()->addItem(modeList.at(i), modeDataList.at(i));
    }
}

void WallpaperUi::setDisplayTypes(const QStringList &typeList, const QStringList &typeDataList)
{
    if (typeList.size() != typeDataList.size()) {
        qWarning()<<"typeList.size():"<<typeList.size()<<" != typeDataList.size():"<<typeDataList.size();
        return;
    }
    typeWidget->comboBox()->clear();
    for (int i = 0; i < typeList.size(); ++i) {
        typeWidget->comboBox()->addItem(typeList.at(i), typeDataList.at(i));
    }
}

void WallpaperUi::setWallpaperMode(const QString &mode, const QString &data)
{
    modeWidget->comboBox()->setCurrentText(mode);
    if (modeWidget->comboBox()->currentData().toString() == "color") {
        currentFile = "";
        QColor color(data);
        previewLabel->setColor(color);
        previewLabel->update();
        if (prePictureUnit != nullptr) {
            prePictureUnit->changeClickedFlag(false);
            prePictureUnit->setStyleSheet("border-width: 0px;");
            prePictureUnit = nullptr;
        }
    } else {
        currentFile = data;
        previewLabel->setLocalPixmap(QPixmap(currentFile));
        previewLabel->update();
        resetClickedPic();
    }
}

void WallpaperUi::setDisplayType(const QString &type)
{
    typeWidget->comboBox()->setCurrentText(type);
    previewLabel->setMode(typeWidget->comboBox()->currentData().toString());
    previewLabel->update();
}

void WallpaperUi::setPicturesFile(QList<PictureInfo*> picInfoList) {
    bool hitCurrentFile = false;
    for (int i = 0; i < picInfoList.size(); ++i) {
        QString name = picInfoList.at(i)->fileName;
        bool clicked = false;
        if (name == currentFile) {
            clicked = true;
            hitCurrentFile = true;
        }
        PictureUnit *picUnit = new PictureUnit();
        if (picUnit == nullptr) {
            continue;
        }
        picUnit->setPixmap(picInfoList.at(i)->pixmap);
        picUnit->setFilenameText(name);
        createPictureUnit(picUnit, clicked);
    }
    // 是自定义的图片
    if (!currentFile.isEmpty() && !hitCurrentFile && QFile::exists(currentFile)) {
        previewLabel->setLocalPixmap(QPixmap(currentFile));
        previewLabel->update();
    }
}

void WallpaperUi::createPictureUnit(PictureUnit* picUnit, const bool &clicked) {
    if (picUnit == nullptr)
        return;
    const QString &filename = picUnit->filenameText();
    if (clicked) {
        prePictureUnit = picUnit;
        picUnit->changeClickedFlag(true);
        previewLabel->setLocalPixmap(QPixmap(filename));
        previewLabel->update();
    }
    connect(picUnit, &PictureUnit::clicked, [=](QString file){
        if (prePictureUnit) {
            prePictureUnit->changeClickedFlag(false);
        }
        prePictureUnit = picUnit;
        previewLabel->setLocalPixmap(QPixmap(file));
        previewLabel->update();
        Q_EMIT wallpaperChanged("picture", file);
    });
    pictureLayout->addWidget(picUnit);
}

void WallpaperUi::showPictures()
{
    colorGroup->setHidden(true);
    typeWidget->setHidden(false);
    picFrame->setHidden(false);
    bottomFrame->setHidden(false);
}

void WallpaperUi::showColors()
{
    picFrame->setHidden(true);
    typeWidget->setHidden(true);
    colorGroup->setHidden(false);
    bottomFrame->setHidden(true);
}

void WallpaperUi::resetClickedPic() {
    if (prePictureUnit != nullptr) {
        prePictureUnit->changeClickedFlag(false);
        prePictureUnit = nullptr;
    }
    for (int i = pictureLayout->count() - 1; i >= 0; --i) {
        QLayoutItem *it      = pictureLayout->itemAt(i);
        PictureUnit *picUnit = static_cast<PictureUnit*>(it->widget());
        if (currentFile == picUnit->filenameText()) {
            picUnit->changeClickedFlag(true);
            prePictureUnit = picUnit;
        }
    }
}
