
#include "packagelistjob.h"
#include "package.h"
#include "packageimpl.h"
#include "nodefilter.h"

#include <qregexp.h>

#include <dom/dom_element.h>
#include <dom/html_inline.h>
#include <dom/dom_text.h>

#include <kdebug.h>
#include <assert.h>

const char *PackageListJob::s_packageListURL = "http://bugs.kde.org/db/ix/packages.html";

PackageListJob::PackageListJob()
{
}

PackageListJob::~PackageListJob()
{
}

void PackageListJob::start()
{
    HTMLBugJob::start( KURL( QString::fromLatin1( s_packageListURL ) ) );
}

void PackageListJob::process()
{
    m_packages.clear();

    QStringList tags;
    tags << "li";

    processFiltered( tags ); 

    emit packageListAvailable( m_packages );
}

void PackageListJob::processNode( const DOM::Node &n )
{
    DOM::Element e = n;
    DOM::HTMLAnchorElement anchor = e.firstChild();
    if ( anchor.isNull() )
        return;

    DOM::Text pkgTextElement = anchor.firstChild();
    QString pkgName = pkgTextElement.data().string();
    if ( pkgName.isEmpty() )
        return;

    // parse "  (42 bugs; "
    DOM::Text nrOfBugsText = anchor.nextSibling();
    QString txt = nrOfBugsText.data().string(); 
    int bracePos = txt.find( '(' );
    int bugsPos = txt.find( QString::fromLatin1( "bug" ) );

    if ( bracePos == -1 || bugsPos == -1 ||
            bracePos >= bugsPos )
        return;

    bool ok = false;
    uint bugCount = txt.mid( bracePos + 1, bugsPos - bracePos + 1 ).toUInt( &ok );
    if ( !ok )
        bugCount = 0; // could be 'no outstanding bugs', although we should
                      // probably check for that one explicitly

    DOM::Node nextSibling = nrOfBugsText.nextSibling();
    if ( nextSibling.isNull() )
        return;

    DOM::Text maintainerElement = nextSibling.firstChild();
    if ( maintainerElement.isNull() )
        return;

    Person p = Person::parseFromString( maintainerElement.data().string() );

    PackageImpl *pkg = new PackageImpl( pkgName, bugCount, p );
    m_packages.append( Package( pkg ) );
}

#include "packagelistjob.moc"

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