#include "translationmanager.h"

#include <QApplication>
#include <QTranslator>

TranslationManager::TranslationManager()
{

}

void TranslationManager::checkIfTranslationDirIsAvailable()
{
    findTranslationDir(true);
}

QTranslator* TranslationManager::loadTranslation(QString moduleName)
{
    QLocale locale;
    QTranslator* pTranslator = new QTranslator();
    if (pTranslator->load(
                locale,
                moduleName, QLatin1String("_"),
                findTranslationDir(false).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 moule " << moduleName <<
                    " found for current locale " << locale;
    }
    return pTranslator;
}

QDir TranslationManager::findTranslationDir(bool logToCommandline)
{
    // 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
    QDir translationDir;
    if ( QFile("../translations/packagesearch_de.qm").exists() )
       translationDir = QDir("../translations/");
    else if ( QFile("translations/packagesearch_de.qm").exists() )
       translationDir = QDir("translations/");
    else if ( QFile("/usr/share/packagesearch/translations/packagesearch_de.qm").exists() )
       translationDir = QDir("/usr/share/packagesearch/translations");
    else if (logToCommandline)
       qWarning("Unable to locate translation directory, translations must be located in "
           "/usr/share/packagesearch/translations, ../translations or translations/.");
    if (logToCommandline)
       qDebug() << "Translation dir " << translationDir.path();
    return translationDir;
}
