
#include "bugjob.h"

#include "kbbprefs.h"

#include <tdeio/job.h>

#include <string.h>
#include <tdelocale.h>
#include <kdebug.h>

BugJob::BugJob( BugServer *server )
    : Job( false ), mServer( server )
{
}

BugJob::~BugJob()
{
}

void BugJob::start( const KURL &url )
{
    kdDebug() << "BugJob::start(): " << url.url() << endl;

    if ( KBBPrefs::instance()->mDebugMode ) {
        BugSystem::saveQuery( url );
    }

    // ### obey post, if necessary

    TDEIO::Job *job = TDEIO::get( url, true /*always 'reload=true', we have our own cache*/, false );

    connect( job, TQ_SIGNAL( result( TDEIO::Job * ) ),
             this, TQ_SLOT( ioResult( TDEIO::Job * ) ) );
    connect( job, TQ_SIGNAL( data( TDEIO::Job *, const TQByteArray & ) ),
             this, TQ_SLOT( ioData( TDEIO::Job *, const TQByteArray & ) ) );
    connect( job, TQ_SIGNAL( infoMessage( TDEIO::Job *, const TQString & ) ),
             this, TQ_SLOT( ioInfoMessage( TDEIO::Job *, const TQString & ) ) );
    connect( job, TQ_SIGNAL( percent( TDEIO::Job *, unsigned long ) ),
             this, TQ_SLOT( ioInfoPercent( TDEIO::Job *, unsigned long ) ) );
}

void BugJob::ioResult( TDEIO::Job *job )
{
    m_error = job->error();
    m_errorText = job->errorText();

    if ( job->error() )
    {
        emit error( m_errorText );
        BugSystem::self()->unregisterJob(this);
        this->kill();
        return;
    }

    infoMessage( i18n( "Parsing..." ) );

#if 0
    kdDebug() << "--START:" << m_data << ":END--" << endl;
#endif

    if ( KBBPrefs::instance()->mDebugMode ) {
        BugSystem::saveResponse( m_data );
    }

    process( m_data );
    infoMessage( i18n( "Ready." ) );

    emit jobEnded( this );

    delete this;
}

void BugJob::ioData( TDEIO::Job *, const TQByteArray &data )
{
    unsigned int start = m_data.size();

    m_data.resize( m_data.size() + data.size() );
    memcpy( m_data.data() + start, data.data(), data.size() );
}

void BugJob::ioInfoMessage( TDEIO::Job *, const TQString &_text )
{
    TQString text = _text;
    emit infoMessage( text );
}

void BugJob::ioInfoPercent( TDEIO::Job *, unsigned long percent )
{
    emit infoPercent( percent );
}

#include "bugjob.moc"
