/*
Copyright (c) 2006  Nikolaj Hald Nielsen <nhnFreespirit@gmail.com>

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Library General Public License for more details.

You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB.  If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/

#include "amarok.h"
#include "debug.h"
#include "magnatunedatabasehandler.h"
#include "magnatunepurchasehandler.h"
#include "statusbar.h"

#include <ktempdir.h>

#include <tqdir.h>
#include <tqfile.h>
#include <tqmessagebox.h>

MagnatunePurchaseHandler::MagnatunePurchaseHandler()
        : TQObject()
{

    m_downloadDialog = 0;
    m_purchaseDialog = 0;
    m_albumDownloader = 0;
}


MagnatunePurchaseHandler::~MagnatunePurchaseHandler()
{
    delete m_downloadDialog;
    delete m_purchaseDialog;
    delete m_albumDownloader;
}


void MagnatunePurchaseHandler::purchaseAlbum( const MagnatuneAlbum &album )
{
    m_currentAlbum = album;

    //first lets get the album cover for the album we are about to purchase.
    //Then we can show it on the purchase dialog as well as put it in the
    //same directory as the album.

    TQString albumCoverUrlString = album.getCoverURL();

    if ( m_albumDownloader == 0 )
    {
        m_albumDownloader = new MagnatuneAlbumDownloader();
        connect( m_albumDownloader, TQ_SIGNAL( coverDownloadCompleted( TQString ) ), this, TQ_SLOT( showPurchaseDialog( TQString ) ) );
    }

    m_currentAlbumCoverName = album.getName() + " - cover.jpg";


    m_albumDownloader->downloadCover( albumCoverUrlString, m_currentAlbumCoverName );

}

void MagnatunePurchaseHandler::showPurchaseDialog(  TQString coverTempLocation )
{

    if ( m_albumDownloader != 0 )
    {
        delete m_albumDownloader;
        m_albumDownloader = 0;
    }

    if ( m_purchaseDialog == 0 )
    {
        m_purchaseDialog = new MagnatunePurchaseDialog( m_parent, "PurchaseDialog", true, 0 );

        connect( m_purchaseDialog, TQ_SIGNAL( makePurchase( TQString, TQString, TQString, TQString, TQString, TQString, int ) ), this, TQ_SLOT( processPayment( TQString, TQString, TQString, TQString, TQString, TQString, int ) ) );
        connect ( m_purchaseDialog, TQ_SIGNAL( cancelled() ), this, TQ_SLOT( albumPurchaseCancelled() ) );
    }





    if ( m_currentAlbum.getId() != 0 )
    {

        KTempDir tempDir;
        m_purchaseDialog->setAlbum( m_currentAlbum );
        m_purchaseDialog->setCover( coverTempLocation + m_currentAlbumCoverName );
        m_purchaseDialog->show();
    }
}

void MagnatunePurchaseHandler::processPayment( TQString ccNumber, TQString expYear, TQString expMonth, TQString name, TQString email, TQString albumCode, int amount )
{
    TQString amountString;
    amountString.setNum( amount, 10 );

    TQString purchaseURL = "https://magnatune.com/buy/buy_dl_cc_xml?cc=" + ccNumber + "&mm=" + expMonth + "&yy=" + expYear + "&sku=" + albumCode + "&name=" + name + "&email=" + email + "&id=amarok&amount=" + amountString;

    TQString debugPurchaseURL = "https://magnatune.com/buy/buy_dl_cc_xml?cc=**********&mm=**&yy=**&sku=" + albumCode + "&name=" + name + "&email=********&id=amarok&amount=" + amountString;
    debug() << "purchase url : " << debugPurchaseURL << endl;

    m_resultDownloadJob = TDEIO::storedGet( KURL( purchaseURL ), false, false );
    Amarok::StatusBar::instance() ->newProgressOperation( m_resultDownloadJob ).setDescription( i18n( "Processing Payment" ) );

    connect( m_resultDownloadJob, TQ_SIGNAL( result( TDEIO::Job* ) ), TQ_SLOT( xmlDownloadComplete( TDEIO::Job* ) ) );


}

void MagnatunePurchaseHandler::xmlDownloadComplete( TDEIO::Job * downloadJob )
{

    debug() << "xml download complete" << endl;

    if ( !downloadJob->error() == 0 )
    {
        //TODO: error handling here
        return ;
    }
    if ( downloadJob != m_resultDownloadJob )
        return ; //not the right job, so let's ignore it

    TDEIO::StoredTransferJob* const storedJob = static_cast<TDEIO::StoredTransferJob*>( downloadJob );
    TQString resultXml = TQString( storedJob->data() );

    debug() << endl << endl << "result: " << resultXml << endl << endl;


    if ( m_albumDownloader == 0 )
    {
        m_albumDownloader = new MagnatuneAlbumDownloader();
        connect( m_albumDownloader, TQ_SIGNAL( downloadComplete( bool ) ), this, TQ_SLOT( albumDownloadComplete( bool ) ) );
    }

    if ( m_downloadDialog == 0 )
    {
        m_downloadDialog = new MagnatuneDownloadDialog( m_parent, "downloaddialog", true, 0 );
        connect( m_downloadDialog, TQ_SIGNAL( downloadAlbum( MagnatuneDownloadInfo * ) ), m_albumDownloader, TQ_SLOT( downloadAlbum( MagnatuneDownloadInfo * ) ) );

    }




    MagnatuneDownloadInfo * downloadInfo = new MagnatuneDownloadInfo();
    if ( downloadInfo->initFromString( resultXml ) )
    {


        downloadInfo->setAlbumId( m_currentAlbum.getId() );

        saveDownloadInfo( resultXml );
        m_downloadDialog->setDownloadInfo( downloadInfo );
        //m_purchaseDialog->close();
        delete m_purchaseDialog;
        m_purchaseDialog = 0;
        m_downloadDialog->show();
    }
    else
    {

        TQMessageBox::information( m_parent, "Could not process payment",
                                  "There seems to be an error in the information entered (check the credit card number), please try again\n" );
        m_purchaseDialog->setEnabled( true );
    }
}


void MagnatunePurchaseHandler::setParent( TQWidget * parent )
{
    m_parent = parent;

}

void MagnatunePurchaseHandler::saveDownloadInfo( TQString infoXml )
{

    TQDir purchaseDir( Amarok::saveLocation( "magnatune.com/purchases/" ) );

    debug() << "magnatune save location" << purchaseDir.absPath() << endl;

    //if directory does not exist, create it
    if ( ! purchaseDir.exists () )
    {
        purchaseDir.mkdir( ".", false );
    }

    //Create file name
    MagnatuneArtist artist = MagnatuneDatabaseHandler::instance() ->getArtistById( m_currentAlbum.getArtistId() );
    TQString artistName = artist.getName();
    TQString fileName = artistName + " - " + m_currentAlbum.getName();

    TQFile file( purchaseDir.absPath() + "/" + fileName );

    //Skip if file already exists
    if ( file.exists () )
        return ;

    //write info
    if ( file.open( IO_WriteOnly ) )
    {
        TQTextStream stream( &file );
        stream << infoXml << "\n";
        file.close();
    }
}

void MagnatunePurchaseHandler::albumDownloadComplete( bool success )
{
    //cleanup time!

    debug() << "MagnatunePurchaseHandler::albumDownloadComplete" << endl;

    delete m_downloadDialog;
    m_downloadDialog = 0;

    emit( purchaseCompleted( success ) );

}

void MagnatunePurchaseHandler::albumPurchaseCancelled( )
{
    debug() << "Purchased dialog cancelled, deleting..." << endl;

    delete m_purchaseDialog;
    m_purchaseDialog = 0;


    emit( purchaseCompleted( false ) );
}







#include "magnatunepurchasehandler.moc"



