
#include <KConfig>
#include <KConfigGroup>
#include <KToolInvocation>

#include <QStringList>
#include <QtDebug>

int main(int argc, char **argv)
{
    if (argc == 1)
        return 1;

    qDebug() << "processing" << argv[1];

    // separate query string
    QStringList parts = QString(argv[1]).split('?');

    KConfig config("khelpcenterrc");
    KConfigGroup group(&config, parts[0]);
    QString urlTemplate = group.readEntry( "url", QString());
    if (urlTemplate.isEmpty())
    {
        qWarning() << "could not find url template";
        return 2;
    }

    // get language
    QStringList keys = parts[0].split('/');
    QString fileName = keys[keys.size()-2] + "rc";
    KConfig appConfig(fileName);
    QString language;
    if (appConfig.hasGroup("Locale"))
    {
        KConfigGroup localeGroup(&appConfig, "Locale");
        language = localeGroup.readEntry( "Language", QString());
        qDebug() << language << "read from application config file";
    }
    if (language.isEmpty())
    {
        KConfig globalConfig("kdeglobals");
        if (globalConfig.hasGroup("Locale"))
        {
            KConfigGroup localeGroup(&globalConfig, "Locale");
            language = localeGroup.readEntry( "Language", QString());
            qDebug() << language << "read from global config file";
        }
    }
    if (language.isEmpty())
    {
        language = "en";
        qDebug() << "using default language" << language;
    }

    QString url = urlTemplate;
    url.replace("@Language@", language);

    // convert anchor into html page
    if (parts.size() > 1)
    {
        QString q = parts[1];
        q.replace("anchor=", "");
        url.replace("index", q);
    }

    KToolInvocation::invokeBrowser(url);
    return 0;
}
