#include "translation_manager.h"

#include <QCoreApplication>
#include <QDebug>

TranslationManager::TranslationManager(QObject* parent)
    : QObject(parent) {
}

bool TranslationManager::setLanguage(const QString& language) {
    if (language == m_language) {
        return true;
    }

    if (language.isEmpty()) {
        if (m_translator) {
            QCoreApplication::removeTranslator(m_translator.get());
            m_translator.reset();
        }
        m_language.clear();
        ++m_retranslateToken;
        emit retranslateTokenChanged();
        emit languageChanged();
        return true;
    }

    auto translator = std::make_unique<QTranslator>();
    const QString qmPath = QStringLiteral(":/i18n/app_%1.qm").arg(language);
    if (!translator->load(qmPath)) {
        qWarning() << "Failed to load translation:" << language;
        return false;
    }

    if (m_translator) {
        QCoreApplication::removeTranslator(m_translator.get());
    }
    m_translator = std::move(translator);
    QCoreApplication::installTranslator(m_translator.get());

    m_language = language;
    ++m_retranslateToken;
    emit retranslateTokenChanged();
    emit languageChanged();
    return true;
}
