/**
 * 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 "productcatalogmodel.h"

#include <QDebug>
#include <QGraphicsObject>

#include "declarativepurchaselistmodel.h"
#include "myqmlapplicationviewer.h"
#include "purchasableitembase.h"

ProductCatalogModel::ProductCatalogModel(QObject *parent) :
    QSortFilterProxyModel(parent),
    m_iapModel(0)
{
    m_iapModel = new DeclarativePurchaseListModel(this);
    setSourceModel(m_iapModel);
    setDynamicSortFilter(false);
    sort(0);

    connect(m_iapModel, SIGNAL(applicationBusyChanged()), this, SLOT(modelBusyChanged()));
    connect(m_iapModel, SIGNAL(purchaseCompleted(bool)), this, SLOT(purchaseCompleted(bool)));
}

bool ProductCatalogModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
{
    //sort in activation order. Not purchased items go first
    PurchasableItemBase* dataLeft = m_iapModel->record(left);
    PurchasableItemBase* dataRight = m_iapModel->record(right);

    if (dataLeft && dataLeft->isActivated() && !(dataRight && dataRight->isActivated()))
        return false;

    return true;
}

void ProductCatalogModel::modelUpdated()
{
    qDebug() << "model was re-sorted";
    sort(0);
}

void ProductCatalogModel::buy(int idx)
{
    QModelIndex recIdx = mapToSource(index(idx, 0));

    m_iapModel->buy(recIdx);
}

void ProductCatalogModel::restoreProducts()
{
    m_iapModel->restoreProducts();
}

void ProductCatalogModel::getUserInfo()
{
    m_iapModel->getUserInfo();
}

QImage ProductCatalogModel::createIcon(int idx)
{
    QModelIndex recIdx = mapToSource(index(idx, 0));

    PurchasableItemBase* record = m_iapModel->record(recIdx);
    if (record){
        return (record->stateIcon());
    }
    
    return (QImage());
}

bool ProductCatalogModel::isApplicationBusy() const
{
    return m_iapModel->m_isApplicationBusy;
}

void ProductCatalogModel::modelBusyChanged()
{
    emit applicationBusyChanged();
}

void ProductCatalogModel::purchaseCompleted(bool status)
{
    emit appPurchaseCompleted(QVariant(status));
}
