/*
 * Copyright (C) 2022 Guido Berhoerster <guido+ubports@berhoerster.name>
 *
 * This file is part of Lomiri Clock App
 *
 * Clock App is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Clock App is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <QDebug>
#include <glib.h>
#include <geonames.h>

#include "geonamestimezonemodel.h"

GeonamesTimeZoneModel::GeonamesTimeZoneModel(QObject *parent):
    TimeZoneModel(parent)
{
}

QString GeonamesTimeZoneModel::query() const
{
    return m_query;
}

void GeonamesTimeZoneModel::setQuery(const QString &query)
{
    if (m_query == query) {
        // Don't set the query again if it is the same query being set again
        return;
    }

    // Update the query and Q_EMIT the changed signal to let QML know
    m_query = query;
    Q_EMIT queryChanged();

    setStatus(TimeZoneModel::Loading);

    // Start the retrieval process
    loadTimeZonesFromGeonames();
}

void GeonamesTimeZoneModel::loadTimeZonesFromGeonames()
{
    geonames_query_cities(m_query.toUtf8().constData(), GEONAMES_QUERY_DEFAULT, NULL,
        (GAsyncReadyCallback)(GeonamesTimeZoneModel::queryFinished), static_cast<void *>(this));
}

void GeonamesTimeZoneModel::queryFinished(GObject *source_object, GAsyncResult *result, gpointer user_data)
{
    Q_UNUSED(source_object);
    GeonamesTimeZoneModel *model = static_cast<GeonamesTimeZoneModel *>(user_data);
    guint len;
    GError *err = nullptr;
    gint *cities = geonames_query_cities_finish(result, &len, &err);
    if(err != nullptr) {
        qDebug() << "[LOG] Geonames processing error: " << err->message;
        g_error_free(err);

        model->setStatus(TimeZoneModel::Error);

        return;
    }

    model->updateModel(cities, len);

    g_free(cities);
}

void GeonamesTimeZoneModel::updateModel(gint *cities, guint len)
{
    // Let QML know model is being reset and rebuilt
    beginResetModel();

    m_citiesData.clear();

    for (guint i = 0; i < len; i++) {
        CityData cityData;

        GeonamesCity *city = geonames_get_city(cities[i]);

        cityData.cityId = QString::fromUtf8(geonames_city_get_name(city));
        cityData.cityName = cityData.cityId;

        auto state = QString::fromUtf8(geonames_city_get_state(city));
        auto country = QString::fromUtf8(geonames_city_get_country(city)); 

        if (!state.isEmpty()) {
            cityData.countryName = QString("%1, %2").arg(state).arg(country);
        } else {
            cityData.countryName = country;
        }

        cityData.timeZone = QTimeZone(QByteArray(geonames_city_get_timezone(city)));

        m_citiesData.append(cityData);
    }

    setStatus(TimeZoneModel::Ready);

    // Let QML know model is reusable again
    endResetModel();
}
