/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license.txt -file, included in
 * the distribution.
 */

#include "purchasableitem.h"

#include <QApplication>
#include <QDebug>
#include <QDir>

#include "catalog_constants.h"
#include "declarativepurchaselistmodel.h"
#include "drmfile.h"

#define QMLICONRESOURCE_NOTREADY "/qml/mototrialracer/in_application_billing/gfx/notready.png"

PurchasableItem::PurchasableItem(DeclarativePurchaseListModel &model,
                                 const QString &productID,
                                 const QString &productUrl):
    PurchasableItemBase(model, productID, productUrl)
{
    m_productMetadata.drmProtection = IAPClient::OtherDrm;

    QString filepath(productUrl);
    filepath.replace(QString(KProtectedCatalog), QString(KProductIcon));
    filepath.append( + "/" + QString(KProductBuyIcon));

    m_buy_icon = new QImage(filepath);
    
    if (isPurchased()){
        m_unlocked_icon =  new QImage(*m_buy_icon); // use copy constructor because
                                                   // 'm_unlocked_icon' and 'm_buy_icon' are
                                                   // deleted in the base class destructor
                                                   // separatelly
    }
    //NOTE: the condittion (m_unlocked_icon == NULL) indicates locked content

    m_notready_icon = new QImage(QApplication::applicationDirPath() + QMLICONRESOURCE_NOTREADY);
    m_productUrl.append("/");
    m_productUrl.append(KProtectedResource);
}

void PurchasableItem::setUnlocked(QString* purchaseTicket)
{
    saveTicket(purchaseTicket);
    bool success = true;

    QDir currentDir(m_productUrl);
    QStringList files = currentDir.entryList();
    
    foreach (QString filepath, files){
        DRMFile file;
        int error = file.open(m_productUrl + "/" + filepath);
        //IMPORTANT NOTE: Access to unprotected content is unrestricted by CAF
        //thus the checking below will pass for ordinary non-protected files
        success = (success && (error == KErrNone));


        if (!success){
            file.close();
            break;
        }

        //DRM protected file is unlocked
        qDebug() << "start iterating DRM file";
        for (int i = 0; i < file.count(); i++){
            QString tmp(file.getName(i));
            qDebug() << "DRM file : <" << tmp << ">";
        }

        file.close();
    }


    if (success){
        delete m_unlocked_icon; // just in case to prevent possible memory leak
        m_unlocked_icon =  new QImage(*m_buy_icon);
    }
}

bool PurchasableItem::isPurchased()
{
    return readTicket();
}
