/*
 * Squawk messenger.
 * Copyright (C) 2019  Yury Gubich <blue@macaw.me>
 *
 * 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 of the License, 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 <QIcon>
#include <QPainter>
#include <QFileInfo>

#include <KConfigCore/KSharedConfig>
#include <KConfigCore/KConfigGroup>
#include <KConfigWidgets/KColorScheme>

QPixmap createPixmap(int size, const QBrush& window, const QBrush& button, const QBrush& view, const QBrush& selection);

extern "C" QIcon* createPreview(const QString& path) {
    KSharedConfigPtr schemeConfig = KSharedConfig::openConfig(path);
    QIcon* result = new QIcon();
    KColorScheme activeWindow(QPalette::Active, KColorScheme::Window, schemeConfig);
    KColorScheme activeButton(QPalette::Active, KColorScheme::Button, schemeConfig);
    KColorScheme activeView(QPalette::Active, KColorScheme::View, schemeConfig);
    KColorScheme activeSelection(QPalette::Active, KColorScheme::Selection, schemeConfig);

    result->addPixmap(createPixmap(16, activeWindow.background(), activeButton.background(), activeView.background(), activeSelection.background()));
    result->addPixmap(createPixmap(24, activeWindow.background(), activeButton.background(), activeView.background(), activeSelection.background()));

    return result;
}

extern "C" void deletePreview(QIcon* icon) {
    delete icon;
}

extern "C" void colorSchemeName(const QString& path, QString& answer) {
    KSharedConfigPtr config = KSharedConfig::openConfig(path);
    KConfigGroup group(config, QStringLiteral("General"));
    answer = group.readEntry("Name", QFileInfo(path).baseName());
}

extern "C" void createPalette(const QString& path, QPalette& answer) {
    KSharedConfigPtr config = KSharedConfig::openConfig(path);
    answer = KColorScheme::createApplicationPalette(config);
}

QPixmap createPixmap(int size, const QBrush& window, const QBrush& button, const QBrush& view, const QBrush& selection) {
    QPixmap pix(size, size);
    pix.fill(Qt::black);
    QPainter p;
    p.begin(&pix);
    const int itemSize = size / 2 - 1;
    p.fillRect(1, 1, itemSize, itemSize, window);
    p.fillRect(1 + itemSize, 1, itemSize, itemSize, button);
    p.fillRect(1, 1 + itemSize, itemSize, itemSize, view);
    p.fillRect(1 + itemSize, 1 + itemSize, itemSize, itemSize, selection);
    p.end();
    return pix;
}