#include "SkinApplier.h"
#include "ui_SkinApplier.h"

#include "SkinSettings.h"
#include "OpenRGBSkinPlugin.h"
#include "SkinsLoader.h"
#include <QFileDialog>
#include <QTextStream>
#include <QDesktopServices>
#include <QUrl>

SkinApplier::SkinApplier(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SkinApplier)
{
    ui->setupUi(this);
    app = dynamic_cast<QApplication*>(QApplication::instance());

    std::vector<std::string> skins = SkinsLoader::GetSkinFileNames();

    for(std::string skin:skins)
    {
        ui->skins_list->addItem(QString::fromStdString(skin));
    }
}

SkinApplier::~SkinApplier()
{
    delete ui;
}

void SkinApplier::SetSkin(std::string filename)
{
    app->setStyleSheet(SkinsLoader::LoadFileFromSkinsFolder(QString::fromStdString(filename)));
};

void SkinApplier::on_open_skin_file_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open skin file"), "", tr("QSS Files (*.qss)"));
    app->setStyleSheet(SkinsLoader::LoadFile(fileName));
}

void SkinApplier::on_apply_skin_clicked()
{
    QString skin = ui->skins_list->currentText();

    if(skin.isEmpty())
    {
        return;
    }

    app->setStyleSheet(SkinsLoader::LoadFileFromSkinsFolder(skin));
}

void SkinApplier::on_open_skins_folder_clicked()
{
    filesystem::path config_dir = OpenRGBSkinPlugin::RMPointer->GetConfigurationDirectory() / "plugins" / "skins";
    QUrl url = QUrl::fromLocalFile(QString::fromStdString(config_dir.string()));

    printf("Opening %s\n", url.path().toStdString().c_str());

    QDesktopServices::openUrl(url);
}

void SkinApplier::on_load_at_startup_stateChanged(int)
{
    json settings;

    if(ui->load_at_startup->isChecked())
    {
        settings["load_at_startup"] = ui->skins_list->currentText().toStdString();
    }

    SkinSettings::SaveSettings(settings);
}
