#include "artworkcolorprovider.h"

#include <QColor>
#include <QImage>
#include <QLoggingCategory>

Q_DECLARE_LOGGING_CATEGORY(dcStreamUnlimited)

ArtworkColorProvider::ArtworkColorProvider(NetworkAccessManager *nam, QObject *parent) : QObject(parent),
    m_nam(nam)
{

}

void ArtworkColorProvider::setArtworkUrl(const QString &artworkUrl)
{
    QNetworkRequest request(artworkUrl);
    QNetworkReply *reply = m_nam->get(request);
    connect(reply, &QNetworkReply::finished, reply, &QNetworkReply::deleteLater);
    connect(reply, &QNetworkReply::finished, this, [this, reply](){
        if (reply->error() != QNetworkReply::NoError) {
            qCWarning(dcStreamUnlimited) << "Error fetching artwork image:" << reply->errorString();
            m_artworkColor = Qt::white;
            emit artworkColorChanged(m_artworkColor);
            return;
        }

        QByteArray imageData = reply->readAll();
        QString contentTypeString = reply->header(QNetworkRequest::ContentTypeHeader).toString();
        qCDebug(dcStreamUnlimited()) << "Artwork image size" << imageData.size() << contentTypeString;
        QImage image;
        if (contentTypeString.toLower().contains("png")) {
            qCDebug(dcStreamUnlimited()) << "Got PNG artwork image";
            image = QImage::fromData(imageData, "PNG");
        } else if (contentTypeString.toLower().contains("jpg") || contentTypeString.toLower().contains("jpeg")) {
            qCDebug(dcStreamUnlimited()) << "Got JPEG artwork image";
            image = QImage::fromData(imageData, "JPEG");
        } else if (contentTypeString.toLower().contains("pbm")) {
            qCDebug(dcStreamUnlimited()) << "Got PBM artwork image";
            image = QImage::fromData(imageData, "PBM");
        } else if (contentTypeString.toLower().contains("ppm")) {
            qCDebug(dcStreamUnlimited()) << "Got PPM artwork image";
            image = QImage::fromData(imageData, "PPM");
        } else if (contentTypeString.toLower().contains("xbm")) {
            qCDebug(dcStreamUnlimited()) << "Got XBM artwork image";
            image = QImage::fromData(imageData, "XBM");
        } else if (contentTypeString.toLower().contains("xpm")) {
            qCDebug(dcStreamUnlimited()) << "Got XPM artwork image";
            image = QImage::fromData(imageData, "XPM");
        } else {
            qCWarning(dcStreamUnlimited()) << "Got unknown image format" << contentTypeString;
            m_artworkColor = Qt::white;
            emit artworkColorChanged(m_artworkColor);
            return;
        }

        qCDebug(dcStreamUnlimited()) << "Artwork image:" << image;
        m_artworkColor = calculateArtworkDominantColor(image);
        emit artworkColorChanged(m_artworkColor);
    });
}

QColor ArtworkColorProvider::artworkColor() const
{
    return m_artworkColor;
}

QColor ArtworkColorProvider::calculateArtworkDominantColor(const QImage &image)
{

    // Calculate the average color of the image
    int averageRed = 0;
    int averageGreen = 0;
    int averageBlue = 0;

    for (int x = 0; x < image.size().width(); x++) {
        for (int y = 0; y < image.size().height(); y++) {
            QRgb pixel = image.pixel(x, y);
            averageRed += qRed(pixel);
            averageGreen += qGreen(pixel);
            averageBlue += qBlue(pixel);
        }
    }

    int pixelCount = image.size().width() * image.size().height();
    if (pixelCount <= 0)
        return Qt::black;

    return QColor(averageRed / pixelCount, averageGreen / pixelCount, averageBlue / pixelCount);
}
