/*
 * This file is part of DesktopBSD, see the README file.
 *
 * Author: Peter Hofer <ph@desktopbsd.net>
 *			(C) 2004, 2005
 *
 * Copyright: BSD, see the COPYING file included in this distribution
 *
 */

#include <qapplication.h>
#include <qtranslator.h>
#include <qtextcodec.h>
#include <qfile.h>
#include <qwizard.h>
#include <qpushbutton.h>
#include <qtextstream.h>

#include <dbsdsettings.h>

#include <translation.h>


/**
  * Returns the used locale, e.g. "de_AT". This method uses
  * QTextCodec::locale() and DesktopBSD's locale mapping file.
  * 
  * @note The used charset is removed from the string.
  */
QString Translation::getLocale() {
	QString locale = QTextCodec::locale();

	/* Remove charset part */
	int pos = locale.find('.');
	if(pos >= 0)
		locale.truncate(pos);

	/* Search for a locale mapping */
	QFile f("/usr/local/share/desktopbsd/translations/locale-map");
	if(f.open(IO_ReadOnly)) {
		QTextStream ts(&f);
		ts.setEncoding(QTextStream::UnicodeUTF8);
		
		bool found = false;
		while(!found && !ts.atEnd()) {
			QStringList parts = QStringList::split(' ', ts.readLine());
		
			if(parts.count() == 2 && parts[0] != '#' && parts[1] == locale) {
				locale = parts[0];
				found = true;
			}
		}
		
		f.close();
	}

	return locale;
}

/** Installs a Translator for user's current locale,
  * e.g. de_AT. Uses Translation::getLocale()
  */
void Translation::installTranslator() {
	installTranslator(getLocale());
}

/** Installs a Translator for the given locale, e.g. "de". */
void Translation::installTranslator(const QString & locale) {
	QTranslator *translator = new QTranslator();
	translator->load(QString("desktopbsd.%1").arg(locale), "/usr/local/share/desktopbsd/translations");
	qApp->installTranslator(translator);
}

void Translation::installInitialConfTranslator() {
	DBSDSettings s;
	installTranslator(s.readEntry("/initialConf/language"));
}

/**
  * Unlike message boxes, QWizard buttons are not translated by default.
  * This method sets localized button texts in the given QWizard object.
  */
void Translation::translateWizard(QWizard *w) {
	if(w != NULL) {
		QString strings[] = {
			tr("< Back"),
			tr("Next >"),
			tr("Finish"),
			tr("Cancel"),
			tr("Help")
		};

		QPushButton *buttons[] = {
			w->backButton(),
			w->nextButton(),
			w->finishButton(),
			w->cancelButton(),
			w->helpButton()
		};

		for(int i = 0; i < (sizeof buttons / sizeof buttons[0]); ++i)
			if(buttons[i] != NULL)
				buttons[i]->setText(strings[i]);
	}
}
