#include "translationmanager.h"

#include <QApplication>
#include <QTranslator>

TranslationManager::TranslationManager()
{

}

QTranslator* TranslationManager::loadTranslation(QString moduleName)
{
    QLocale locale;
    QTranslator* pTranslator = new QTranslator();
    if (pTranslator->load(
                locale,
                moduleName, QLatin1String("_"),
                findTranslationDir(false, moduleName).absolutePath())
            ) {
        qDebug() << "Loaded translation " << moduleName << "_" << locale;
        QApplication::installTranslator(pTranslator);
    } else {
        delete pTranslator;
        pTranslator = 0;
        // warn if we have non-english and no translation
        if (!locale.system().name().startsWith("en_"))
            qInfo() << "No translation for module " << moduleName <<
                    " found for current locale " << locale;
    }
    return pTranslator;
}

QDir TranslationManager::findTranslationDir(bool logToCommandline, QString moduleName)
{
    // TODO: this makes packagesearch not finding the translations if there is a translations directory anywhere
    // replace by search for the concrete translation files
    // setup translation
    QString fileName = moduleName + "_de.qm";
    QDir translationDir;
    if ( QFile("../translations/" + fileName).exists() )
       translationDir = QDir("../translations/");
    else if ( QFile("translations/" + fileName).exists() )
       translationDir = QDir("translations/");
    else if ( QFile("plugins/" + moduleName + "/" + fileName).exists() )
       translationDir = QDir("plugins/" + moduleName + "/");
    else if ( QFile("app/src/" + fileName).exists() )
       translationDir = QDir("app/src/");
    else if ( QFile("/usr/share/packagesearch/translations/" + fileName).exists() )
       translationDir = QDir("/usr/share/packagesearch/translations");
    else if (logToCommandline)
       // todo here, because with QT 6.7 this will most likely change again.
       qWarning() << "Unable to locate translation directory, translations must be located in "
                     "/usr/share/packagesearch/translations, ../translations, TODO or translations/.\n"
                  << "Current working directory: " << QDir().absolutePath();
    if (logToCommandline)
       qDebug() << "Translation dir " << translationDir.path();
    return translationDir;
}
