#include "drmimageprovider.h"
#include <QApplication>
#include <QUrl>
#include <QDebug>

#if defined(USESYMBIANDRM)
#include "DRMFile.h"
#endif

DrmImageProvider::DrmImageProvider()
    : QDeclarativeImageProvider(QDeclarativeImageProvider::Image)
{
}

QImage DrmImageProvider::requestImage(const QString & id, QSize * size, const QSize & requestedSize)
{
    QString path;
    if (id.startsWith("resourceid"))
    {
        path = QUrl(getDrmDataRoot()).toLocalFile();
    }
    else
    {
        path = QUrl(getFreeDataRoot()).toLocalFile();
    }

    path += id;

    qDebug() << "requestImage " << path;

    int width = 100;
    int height = 50;

    if (size)
        *size = QSize(width, height);

    QImage image(requestedSize.width() > 0 ? requestedSize.width() : width,
                 requestedSize.height() > 0 ? requestedSize.height() : height,
                 QImage::Format_ARGB32_Premultiplied);

#if defined(USESYMBIANDRM)
    uchar* buffer = NULL;
    int filesize = 0;
    DRMFile file;
    if(file.open(path) == 0)
    {
        filesize = file.size();
        buffer = new uchar[filesize];
        int result = file.read((char*)buffer, filesize);
        if(result != filesize)
        {
            qDebug() << "Failed to read the file";
            delete [] buffer;
            buffer = NULL;
        }
        file.close();
    }
    else
        qDebug() << "Failed to open the file!" ;

    if(buffer!=NULL)
    {
        if(!image.loadFromData(buffer, filesize))
            qDebug() << "Loading image failed";
    }

    delete [] buffer;
#else
    if(!image.load(path))
    {
        qDebug() << "load failed";
    }
#endif

    return image;
}
