#include <QDebug>
#include <QDir>
#include <QFile>
#include <QSettings>

#include "licensestatus.h"

namespace {
    static const auto ACCEPTED_LICENSE_VERSION_KEY = QStringLiteral("accepted_license_version");
    static const auto PATH_LICENSES = QStringLiteral("/usr/share/docviewer/licenses");
} // namespace

static QString findLicensePath(const QString &prefix, const QString &localeName, bool warn = true)
{
    const static auto suffix = QStringLiteral(".txt");

    QString path = prefix + localeName + suffix;

    if (QFile::exists(path)) {
        return path;
    }

    const static auto englishLocaleName = QStringLiteral("en_US");

    if (localeName != englishLocaleName) {
        if (warn) {
            qWarning() << "LicenseStatus: unable to load locale-specific license for locale" << localeName;
        }
        return findLicensePath(prefix, englishLocaleName, false);
    } else {
        return {};
    }
}

static QString loadLicense(const QString &basePath, const QString &localeName)
{
    const QString path = findLicensePath(basePath, localeName, true);

    if (path.isEmpty()) {
        qWarning() << "LicenseStatus: unable to load either the specified locale or the English license";
        return {};
    }

    QFile file(path);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "LicenseStatus: unable to load license from file" << file.fileName();
        qWarning() << file.errorString();
        return {};
    }

    return QString::fromUtf8(file.readAll());
}

LicenseStatus::LicenseStatus(QObject *parent)
    : QObject(parent)
{
    QSettings settings;
    m_isAccepted = (settings.value(ACCEPTED_LICENSE_VERSION_KEY).toString() == QStringLiteral("1"));
}

bool LicenseStatus::isAccepted() const
{
    return m_isAccepted;
}

void LicenseStatus::accept()
{
    if (!m_isAccepted) {
        QSettings settings;
        settings.setValue(ACCEPTED_LICENSE_VERSION_KEY, QStringLiteral("1"));
        m_isAccepted = true;
        emit isAcceptedChanged();
    }
}

QString LicenseStatus::textLicense(const QString &localeName) const
{
    const QString basePath = PATH_LICENSES + QDir::separator() + QStringLiteral("license-");
    return loadLicense(basePath, localeName);
}
