#include "thumbnailbaritem.h"
#include "imageprovider.h"

#include <QVariant>
#include <QImageReader>
#include <QDebug>

class ThumbnailBarItemPrivate
{
public:
    QObject *item;
    QString id;
};

ThumbnailBarItem::ThumbnailBarItem( QObject *item ) :
    QObject()
{
    p = new ThumbnailBarItemPrivate;
        p->item = item;
        p->id   = ImageProvider::getId();

    connect( p->item , SIGNAL(destroyed()) , this , SLOT(objDestroyed()) );
}

void ThumbnailBarItem::setText( const QString & text )
{
    p->item->setProperty( "text" , text );
}

QString ThumbnailBarItem::text() const
{
    return p->item->property("text").toString();
}

bool ThumbnailBarItem::setPixmap( const QString & path )
{
    QImageReader image( path );
    if( !image.canRead() )
        return false;

    QSize size = image.size();

    p->item->setProperty( "ratio" , (qreal)size.width()/size.height() );
    p->item->setProperty( "source" , "file:/" + path );

    return true;
}

QString ThumbnailBarItem::pixmap() const
{
    return p->item->property("source").toString().remove(0,6);
}

void ThumbnailBarItem::show()
{
    QMetaObject::invokeMethod( p->item , "show" , Qt::QueuedConnection );
}

void ThumbnailBarItem::objDestroyed()
{
    p->item = 0;
    deleteLater();
}

QObject *ThumbnailBarItem::obj() const
{
    return p->item;
}

ThumbnailBarItem::~ThumbnailBarItem()
{
    if( p->item )
    {
        disconnect( p->item , SIGNAL(destroyed()) , this , SLOT(objDestroyed()) );
        delete p->item;
    }

    ImageProvider::addPixmap( p->id , QPixmap() );
    delete p;
}
