#include "timequery.h"
#include <QtCore/QStringList>
#include <QtXmlPatterns/QXmlQuery>
TimeInformation::TimeInformation(const QString &time, const QString &direction)
: m_time(time), m_direction(direction)
{
}
QString TimeInformation::time() const
{
return m_time;
}
QString TimeInformation::direction() const
{
return m_direction;
}
TimeInformation::List TimeQuery::query(const QString &stationId, const QStringList &lineNumbers, const QDateTime &dateTime)
{
const TimeInformation::List information = queryInternal(stationId, dateTime);
TimeInformation::List filteredInformation;
if (!lineNumbers.isEmpty()) {
for (int i = 0; i < information.count(); ++i) {
const TimeInformation info = information.at(i);
for (int j = 0; j < lineNumbers.count(); ++j) {
if (info.direction().startsWith(QString("%1 ").arg(lineNumbers.at(j))))
filteredInformation.append(info);
}
}
} else {
filteredInformation = information;
}
return filteredInformation;
}
TimeInformation::List TimeQuery::queryInternal(const QString &stationId, const QDateTime &dateTime)
{
const QString timesQueryUrl = QString("doc('http://wap.trafikanten.no/F.asp?f=%1&t=%2&m=%3&d=%4&start=1')/wml/card/p/small/a[fn:starts-with(@href, 'Rute')]/string()")
.arg(stationId)
.arg(dateTime.time().hour())
.arg(dateTime.time().minute())
.arg(dateTime.toString("dd.MM.yyyy"));
const QString directionsQueryUrl = QString("doc('http://wap.trafikanten.no/F.asp?f=%1&t=%2&m=%3&d=%4&start=1')/wml/card/p/small/text()[matches(., '[0-9].*')]/string()")
.arg(stationId)
.arg(dateTime.time().hour())
.arg(dateTime.time().minute())
.arg(dateTime.toString("dd.MM.yyyy"));
QStringList times;
QStringList directions;
QXmlQuery query;
query.setQuery(timesQueryUrl);
query.evaluateTo(×);
query.setQuery(directionsQueryUrl);
query.evaluateTo(&directions);
if (times.count() != directions.count())
return TimeInformation::List();
TimeInformation::List information;
for (int i = 0; i < times.count(); ++i)
information.append(TimeInformation(times.at(i).simplified(), directions.at(i).simplified()));
return information;
}