#include "translator.h"
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>

Translator& Translator::instance()
{
    static Translator instance;
    return instance;
}

bool Translator::loadLanguage(const QString& langCode)
{
    QMutexLocker locker(&m_mutex);
    m_translations.clear();

    QString filePath = QStringLiteral(":/resources/translations/%1/resources.json").arg(langCode);
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Failed to open translation file:" << filePath;
        return false;
    }

    QByteArray jsonData = file.readAll();
    file.close();

    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(jsonData, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qWarning() << "Failed to parse translation JSON:" << parseError.errorString();
        return false;
    }

    if (!doc.isObject()) {
        qWarning() << "Translation JSON is not an object";
        return false;
    }

    QJsonObject obj = doc.object();
    for (auto it = obj.begin(); it != obj.end(); ++it) {
        if (it.value().isString()) {
            m_translations.insert(it.key(), it.value().toString());
        }
    }

    m_currentLang = langCode;
    return true;
}

QString Translator::tr(const QString& key) const
{
    QMutexLocker locker(&m_mutex);
    auto it = m_translations.find(key);
    if (it != m_translations.end()) {
        return it.value();
    }
    return key; // fallback to key
}