// (c) 2005 Ian Monroe <ian@monroe.nu>
// See COPYING file for licensing information.

#define DEBUG_PREFIX "RefreshImages"

#include "amarok.h"
#include "collectiondb.h"
#include "debug.h"
#include "refreshimages.h"
#include "statusbar.h"

#include <tqdom.h>
#include <tqimage.h>
#include <tqmap.h>
#include <tqobject.h>
#include <tqstringlist.h>
#include <tqvaluelist.h>
#include <tqvariant.h>

#include <tdeio/job.h>
#include <tdeio/jobclasses.h>
#include <tdeio/scheduler.h>

#include <tdelocale.h>


RefreshImages::RefreshImages()
{
    //"SELECT asin, locale, filename FROM amazon WHERE refetchdate > %1 ;"
    const TQStringList staleImages = CollectionDB::instance()->staleImages();
    TQStringList::ConstIterator it = staleImages.begin();
    TQStringList::ConstIterator end = staleImages.end();

    while( it != end )
    {
        TQString asin=*it;
        it++;
        TQString locale = *it;
        it++;
        TQString md5sum = *it;
        if ( asin.isEmpty() || locale.isEmpty() || md5sum.isEmpty() )
        {
            //somehow we have entries without ASIN
            if ( !md5sum.isEmpty() ) //I've never seen this, just to be sure
                CollectionDB::instance()->removeInvalidAmazonInfo(md5sum);
            it++;
            if ( it==end )
                deleteLater();

            continue;
        }

        TQString url =
            TQString("http://webservices.amazon.%1/onca/xml?Service=AWSECommerceService&SubscriptionId=%2&Operation=ItemLookup&ItemId=%3&ResponseGroup=Small,Images")
             .arg(localeToTLD(locale))
             .arg("0RTQSQ0B8CRY7VX2VF3G2") //Ian Monroe
             .arg(asin);

        debug() << url << endl;

        TDEIO::TransferJob* job = TDEIO::storedGet( url, false, false );
        TDEIO::Scheduler::scheduleJob( job );

        //Amarok::StatusBar::instance()->newProgressOperation( job );
        job->setName( md5sum.ascii() );
        it++; //iterate to the next set

        m_jobInfo[md5sum] = JobInfo( asin, locale, it == end );
        connect( job, TQT_SIGNAL( result( TDEIO::Job* ) ), TQT_SLOT( finishedXmlFetch( TDEIO::Job* ) ) );
    }
}

void
RefreshImages::finishedXmlFetch( TDEIO::Job* xmlJob ) //SLOT
{
    if ( xmlJob->error() )
    {
        Amarok::StatusBar::instance()->shortMessage( i18n( "There was an error communicating with Amazon." ) );
        if ( m_jobInfo[ xmlJob->name() ].m_last )
            deleteLater();

        return;
    }

    TDEIO::StoredTransferJob* const storedJob = static_cast<TDEIO::StoredTransferJob*>( xmlJob );
    const TQString xml = TQString::fromUtf8( storedJob->data().data(), storedJob->data().size() );

    TQDomDocument doc;
    if ( !doc.setContent( xml ) )
      return;

    TQStringList imageSizes;
    imageSizes << "LargeImage" << "MediumImage" << "SmallImage";
    TQString imageUrl;
    foreach( imageSizes )
    {
        TQDomNode imageNode = doc.documentElement()
            .namedItem( "Items" )
            .namedItem( "Item" )
            .namedItem( *it );
        if ( !imageNode.isNull() )
        {
            imageUrl = imageNode.namedItem( "URL" ).firstChild().toText().data();
            if( !imageUrl.isEmpty() )
                break;
        }
    }
    debug() << imageUrl << endl;
    KURL testUrl( imageUrl );
    if( !testUrl.isValid() ) //TDEIO crashs on empty strings!!!
    {
        //Amazon sometimes takes down covers
        CollectionDB::instance()->removeInvalidAmazonInfo(xmlJob->name());
        return;
    }

    TDEIO::TransferJob* imageJob = TDEIO::storedGet( imageUrl, false, false );
    TDEIO::Scheduler::scheduleJob(imageJob);
    //Amarok::StatusBar::instance()->newProgressOperation( imageJob );
    imageJob->setName(xmlJob->name());
    //get the URL of the detail page
    m_jobInfo[xmlJob->name()].m_detailUrl = doc.documentElement()
       .namedItem( "Items" )
       .namedItem( "Item" )
       .namedItem( "DetailPageURL" ).firstChild().toText().data();
    connect( imageJob, TQT_SIGNAL( result(TDEIO::Job*) ), TQT_SLOT( finishedImageFetch(TDEIO::Job*) ) );
}

void RefreshImages::finishedImageFetch(TDEIO::Job* imageJob)
{
   if( imageJob->error() ) {
        Amarok::StatusBar::instance()->shortMessage(i18n("There was an error communicating with Amazon."));
        if(m_jobInfo[imageJob->name()].m_last)
            deleteLater();

        return;
    }
    TQImage img;
    img.loadFromData(static_cast<TDEIO::StoredTransferJob*>(imageJob)->data());
    img.setText( "amazon-url", 0, m_jobInfo[imageJob->name()].m_detailUrl);
    img.save( Amarok::saveLocation("albumcovers/large/") + imageJob->name(), "PNG");

    CollectionDB::instance()->newAmazonReloadDate( m_jobInfo[imageJob->name()].m_asin
        , m_jobInfo[imageJob->name()].m_locale
        , imageJob->name());

    if(m_jobInfo[imageJob->name()].m_last)
        deleteLater();
}

TQString RefreshImages::localeToTLD(const TQString& locale)
{
    if(locale=="us")
        return "com";
    else if(locale=="jp")
        return "co.jp";
    else if(locale=="uk")
        return "co.uk";
    else
        return locale;
}

#include "refreshimages.moc"
