
#include "htmlbugjob.h"
#include "nodefilter.h"

#include <kio/job.h>

#include <khtml_part.h>
#include <klocale.h>

HTMLBugJob::HTMLBugJob()
    : Job( false ), m_part( new KHTMLPart( 0, 0, this ) )
{
}

HTMLBugJob::~HTMLBugJob()
{
    m_node = DOM::Node();
}

void HTMLBugJob::start( const KURL &url /*, const KParts::URLArgs &args*/ )
{
    // ### obey post, if necessary

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

    connect( job, SIGNAL( result( KIO::Job * ) ),
             this, SLOT( ioResult( KIO::Job * ) ) );
    connect( job, SIGNAL( data( KIO::Job *, const QByteArray & ) ),
             this, SLOT( ioData( KIO::Job *, const QByteArray & ) ) );
    connect( job, SIGNAL( infoMessage( KIO::Job *, const QString & ) ),
             this, SLOT( ioInfoMessage( KIO::Job *, const QString & ) ) );
    connect( job, SIGNAL( percent( KIO::Job *, unsigned long ) ),
             this, SLOT( ioInfoPercent( KIO::Job *, unsigned long ) ) );

    m_part->begin( url );
    m_url = url;
}

void HTMLBugJob::processFiltered( const QStringList &tags )
{
    // ###
    if ( m_error ) 
        showErrorDialog();

    // ###
    DOM::HTMLDocument doc = m_node;
    if ( doc.isNull() )
        return;

    NodeFilter *listFilter = new NodeFilter( tags );
    listFilter->ref();

    DOM::NodeFilter f = DOM::NodeFilter::createCustom( listFilter );
    DOM::NodeIterator it = doc.createNodeIterator( doc, DOM::NodeFilter::SHOW_ALL, f, false );

    DOM::Node n = it.nextNode();
    for (; !n.isNull(); n = it.nextNode() )
        processNode( n ); 

    listFilter->deref(); 
}

void HTMLBugJob::processNode( const DOM::Node & )
{
}

void HTMLBugJob::ioResult( KIO::Job *job )
{
    m_part->write( m_data );
    m_part->end();

    m_error = job->error();
    m_errorText = job->errorText();
    m_node = m_part->htmlDocument();
    infoMessage( i18n( "Parsing..." ) );
    process();
    infoMessage( i18n( "Ready." ) );
    
    delete this;
}

void HTMLBugJob::ioData( KIO::Job *, const QByteArray &data )
{
    m_data.append( data );
}

void HTMLBugJob::ioInfoMessage( KIO::Job *, const QString &_text )
{
    QString text = _text;
    emit infoMessage( text );
}

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

#include "htmlbugjob.moc"

/*
 * vim:sw=4:ts=4:et
 */
