File indexing completed on 2024-05-12 04:42:44

0001 /*
0002     SPDX-FileCopyrightText: 2019 Volker Krause <vkrause@kde.org>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "locationutil_p.h"
0008 
0009 #include <KPublicTransport/Location>
0010 #include <KPublicTransport/LocationRequest>
0011 
0012 #include <QCryptographicHash>
0013 
0014 #include <cmath>
0015 
0016 using namespace KPublicTransport;
0017 
0018 bool LocationUtil::sortLessThan(const LocationRequest &request, const Location &lhs, const Location &rhs)
0019 {
0020     if (request.hasCoordinate()) {
0021         return Location::distance(request.latitude(), request.longitude(), lhs.latitude(), lhs.longitude())
0022              < Location::distance(request.latitude(), request.longitude(), rhs.latitude(), rhs.longitude());
0023     }
0024     // for name based search, sort by Levenshtein distance or similar metric
0025     // TODO so far this only sorts for matching or not matching
0026     const auto lhsSame = Location::isSameName(request.name(), lhs.name());
0027     const auto rhsSame = Location::isSameName(request.name(), rhs.name());
0028 
0029     if (lhsSame == rhsSame) {
0030         return lhs.name().compare(rhs.name(), Qt::CaseInsensitive) < 0;
0031     }
0032 
0033     return lhsSame && !rhsSame;
0034 }
0035 
0036 static QString normalizeString(const QString &str)
0037 {
0038     QString n;
0039     n.reserve(str.size());
0040     for (const auto c : str) {
0041         if (c.isLetter() || c.isDigit()) {
0042             n.push_back(c.toCaseFolded());
0043         }
0044     }
0045     return n;
0046 }
0047 
0048 QString LocationUtil::cacheKey(const Location &loc)
0049 {
0050     if (loc.hasCoordinate()) {
0051         return QString::number((int)(loc.latitude() * 1000000)) + QLatin1Char('x') + QString::number((int)(loc.longitude() * 1000000));
0052     }
0053 
0054     QCryptographicHash hash(QCryptographicHash::Sha1);
0055     hash.addData(normalizeString(loc.name()).toUtf8());
0056     hash.addData(normalizeString(loc.streetAddress()).toUtf8());
0057     hash.addData(normalizeString(loc.postalCode()).toUtf8());
0058     hash.addData(normalizeString(loc.locality()).toUtf8());
0059     hash.addData(normalizeString(loc.region()).toUtf8());
0060     hash.addData(normalizeString(loc.country()).toUtf8());
0061 
0062     return QString::fromUtf8(hash.result().toHex());
0063 }