/***************************************************************************
                          findlanguage.cpp  -  description
                             -------------------
    begin                : Tue May 22 2001
    copyright            : (C) 2001 by Ralf Nolden
    email                : nolden@kde.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <stdlib.h>
#include <qstring.h>
#include <qstringlist.h>
#include <ksimpleconfig.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <klocale.h>
#include <kdebug.h>
#include <kdebugclasses.h>


// this code is just copied from kcountrypage.cpp and the unnecessary parts
// are removed
// it should be probably done in one place

static
QStringList loadLanguageList(const QStringList &first)
{
  QStringList prilang;
  // add the primary languages for the country to the list
  for ( QStringList::ConstIterator it = first.begin(); it != first.end(); ++it )
    {
        QString str = locate("locale", *it + QString::fromLatin1("/entry.desktop"));
        if (!str.isNull())
          prilang << str;
    }

  // add all languages to the list
  QStringList alllang = KGlobal::dirs()->findAllResources("locale",
                               QString::fromLatin1("*/entry.desktop"));
  alllang.sort();
  QStringList langlist = prilang;
  langlist += alllang;

  QStringList ret;
  for ( QStringList::ConstIterator it = langlist.begin();
    it != langlist.end(); ++it )
    {
    KSimpleConfig entry(*it);
    entry.setGroup(QString::fromLatin1("KCM Locale"));
    QString name = entry.readEntry(QString::fromLatin1("Name"), i18n("without name"));

    QString tag = *it;
    int index = tag.findRev('/');
    tag = tag.left(index);
    index = tag.findRev('/');
    tag = tag.mid(index+1);
//    combo->insertItem(name, tag, submenu, menu_index);
    ret += tag;
    }
  return ret;
}


QString findLanguage()
{
  KConfig *config = KGlobal::config();
  config->setGroup(QString::fromLatin1("Locale"));

  QString lang = config->readEntry(QString::fromLatin1("Language"));
  lang = lang.lower();
  lang = lang.left(lang.find(':')); // only use the first lang

  QString country = config->readEntry(QString::fromLatin1("Country"),
                                      QString::fromLatin1("C"));
  if(country == QString::fromLatin1("C")) {
    country = QString::fromLatin1(getenv("LANG"));
    if(country.left(5) == "nn_NO") // glibc's nn_NO is KDE's no_NY
      country = "no";
    if(country.contains("_"))
      country = country.mid(country.find("_")+1);
    if(country.contains("."))
      country = country.left(country.find("."));
    if(country.contains("@"))
      country = country.left(country.find("@"));
    if(country != "C")
      country = country.lower();
    if(country == "en") // special-case "en" - should be "en_GB" or "en_US", but plain "en" is in use quite often
      country = "C";
  }

  KSimpleConfig ent(locate("locale",
               QString::fromLatin1("l10n/%1/entry.desktop")
               .arg(country)), true);
  ent.setGroup(QString::fromLatin1("KCM Locale"));
  QStringList langs = ent.readListEntry(QString::fromLatin1("Languages"));
  if (langs.isEmpty()) langs.append(QString::fromLatin1("en_US"));

  QStringList languages = loadLanguageList(langs);

  QString compare = lang;
  if(lang.isEmpty())
  {
    compare = langs.first();
    for(QStringList::Iterator it = langs.begin(); it != langs.end(); ++it)
    {
	if(*it == QString::fromLatin1(getenv("LANG")).mid(3, 2).lower())
	    compare = *it;
    }
  }
  if(compare == "c")
    compare = "C";

  // Find the users's language
  int bestmatch = -1;
  QString best;

  for(QStringList::ConstIterator it = languages.begin();
      it != languages.end();
      ++it)
  {
    int match=0;
    QString l = *it;
    if(l == "C")
	    match++;
    if(l.contains(compare))
	    match+=2;
    if(l.left(compare.length()) == compare)
	    match+=10;
    if(compare == "en_US" && l == "C")
	    match+=50;
    if(l == compare)
	    match+=100;
    if(match > bestmatch) {
	    bestmatch=match;
	    best=l;
    }
  }
  return best;
}
