/***************************************************************************
                          utils.cpp  -  description
                             -------------------
    begin                : December 2007
    copyright            : (c) 2007 by Iven Wold - 526f6c616e642053756368616e
    email                : hour.glass2@yahoo.com
    license              : GPL v 2.0
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This file is part of QTrans.                                          *
 *                                                                         *
 *   QTrans 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; version 2 of the License.               *
 *                                                                         *
 *   QTrans is distributed in the hope that it will be useful,             *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with QTrans. If not, see <http://www.gnu.org/licenses/> or      *
 *   write to the Free Software Foundation, Inc.,                          *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.         *
 *                                                                         *
 ***************************************************************************/

//#include <kconfig.h>		//ooo
//#include <kapplication.h>	//ooo
#include <KConfigGroup>		//ooo
//#include <kglobal.h>		//ooo
//#include <QVariant>		//ooo
//#include <KDebug>		//ooo
#include <QDebug>		//x
#include <KWindowSystem>
#include <KSharedConfig>    //x

#include "qtrans.h"
#include "utils.h"
#include "settings.h"


void QTrans::readConfig()
{
	//KConfig *Conf = kapp->sessionConfig();   //ooo
	//Conf->setGroup("QTrans");   //ooo
	//KConfigGroup cg( KGlobal::config().data(), "QTrans" );   //o
    KConfigGroup cg( KSharedConfig::openConfig(), "QTrans" );  //x

	//English_Path = cg.readEntry("EngDic", "/usr/share/trans/babylon/English.dic");
	English_Path = cg.readEntry("EngDic", "/usr/share/trans/babylon/english.dic");
	compactMode = cg.readEntry("compactMode",false);
	enabled = cg.readEntry("enabled",true);
	AutoPopUp = cg.readEntry("AutoPopUp",true);
	DockIcon = cg.readEntry("DockIcon",true);
	DontClose = cg.readEntry("DontClose",true);
	MouseSelected = cg.readEntry("MouseSelected",false);			//ooo
	StatusBarSelected = cg.readEntry("StatusBarSelected",false);		//ooo
	EnableRecording = cg.readEntry("EnableRecording",false);		//ooo
	StartMin = cg.readEntry("StartMin",false);
	hideTask = cg.readEntry("hideTask",false);
	enableShortCut = cg.readEntry("enableShortCut",true);
	fontType = cg.readEntry("Font", QFont("Courier",16,-1,false));
	//characterFontType = cg.readEntry("characterFont", QFont("Liberation Sans",24,-1,false));

	if (hideTask)
		KWindowSystem::setState(winId(),NET::SkipTaskbar);
/*	else   //ooo
		KWindowSystem::clearState(winId(),NET::SkipTaskbar);
*/
	stayOnTop = cg.readEntry("stayOnTop",false);
	enableAlternates = cg.readEntry("enableAlternates",false);		//ooo
	wordStartsWith = cg.readEntry("wordStartsWith",false);			//ooo
	wholeWordsOnly = cg.readEntry("wholeWordsOnly",false);			//ooo
	wholeStarDict = cg.readEntry("wholeStarDict",false);			//ooo
	this->resize(cg.readEntry("size",QSize(420, 120)));
	ShortKey = cg.readEntry("ShortKey","CTRL+T");
	//closeAct = new KAction( this );  //o
    closeAct = new QAction( this );
	closeAct->setText(i18n("I have been ported, too"));
	connect(closeAct, SIGNAL(triggered(bool)), this, SLOT(slot_ShortCut()));

	if (enableShortCut){
		/*closeAct->setGlobalShortcut( KShortcut(ShortKey),
			KAction::ActiveShortcut | KAction::DefaultShortcut 
		);*/   //o
	} else {
		/*closeAct->setGlobalShortcut( KShortcut(),
			KAction::ActiveShortcut | KAction::DefaultShortcut 
		);*/  //o
	}

	bgColor = cg.readEntry("bgColor",/*"#F7FCAB"*/"#22292F");
	txtColor = cg.readEntry("txtColor",/*"#000000"*/"#AAB1B7");
	expressionTxtColor = cg.readEntry("expressionTxtColor",/*"#000000"*/"#AAB4FF");			//ooo
	sentencePartTxtColor = cg.readEntry("sentencePartTxtColor",/*"#0066FF"*/"#FFAAFF");		//ooo
	widgetStyle = cg.readEntry("widgetStyle","Default");						//ooo
	numberRecodings = cg.readEntry("numberRecodings","30");			//ooo

	//KConfigGroup cg2( KGlobal::config().data(), "Babylon" ); //o
    KConfigGroup cg2( KSharedConfig::openConfig(), "Babylon" );  //x

	int i =  cg2.readEntry("number").toInt();

	QString n;
	for (int j = 0; j < i; j++) {
		n = QString::number(j);

		Dictionary *Item = new Dictionary(
			cg2.readEntry("fileName" + n),
			cg2.readEntry("Language" + n),
			cg2.readEntry("flagID"+n).toInt(),
			//cg2.readEntry("Codec" + n)				//ooo
			//cg2.readEntry("codecID" + n).toInt(),			//ooo
			cg2.readEntry("encodingDefinitionID" + n).toInt(),	//ooo
			cg2.readEntry("directionID" + n).toInt(),		//ooo
			cg2.readEntry("disableID" + n).toInt(),			//ooo
			//cg2.readEntry("encodingID" + n).toInt()		//ooo
			cg2.readEntry("encodingExpressionID" + n).toInt()	//ooo
			);
		bab_dict->append(*Item);

	}

	//KStandardDirs sd;
	//QStringList dirsPath = sd.findDirs("data","qtrans/flags");   //o
	QStringList dirsPath = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QString("qtrans/flags"), QStandardPaths::LocateDirectory);  //x
	//QStringList dirsPath = KStandardDirs::locate("apps", "qtrans/flags");	//ooo
	//QStringList dirsPath = sd.findDirs("apps", "qtrans/flags");		//ooo
	//QStringList dirsPath;							//ooo
	//dirsPath << "/usr/share/kde4/apps/qtrans/flags/";			//ooo
	//QString flagPath = "/usr/share/kde4/apps/qtrans/flags";
	//QStringList::Iterator it = dirsPath.begin();
	QStringList::const_iterator it = dirsPath.constBegin();
	QString flagPath;
	if ( it != dirsPath.constEnd() )
		flagPath = (*it);

	QList<Dictionary>::const_iterator itr;

	for (itr = bab_dict->constBegin(); itr != bab_dict->constEnd(); ++itr) {

		//QPixmap pix("file1.png");
		//QPixmap pix(flagPath+Flag[(*itr).flagID], "png");	//ooo
        QPixmap pix(flagPath+"/"+Flag[(*itr).flagID], "png");	//x
		//QIcon  icon(flagPath+Flag[(*itr).flagID]);		//ooo
        QIcon  icon(flagPath+"/"+Flag[(*itr).flagID]);		//x

		QAction *action;
		//action = new QAction(QIcon(QPixmap(flagPath+Flag[(*itr).flagID])), (*itr).Language, this);  //o
        action = new QAction(QIcon(QPixmap(flagPath+"/"+Flag[(*itr).flagID])), (*itr).Language, this);  //x
		action->setIconVisibleInMenu(true);

		//actionsList.append(languageMenu->addAction(QIcon(QPixmap(flagPath+Flag[(*itr).flagID])), (*itr).Language));
		//actionsList.append(languageMenu->addAction(QIcon(pix), (*itr).Language));
		//actionsList.append(languageMenu->addAction(icon, (*itr).Language));
		//actionsList.append(languageMenu->addAction(action));
		languageMenu->addAction(action);
		actionsList.append(action);
	}

/*******************/

/*	QSettings settings("MySoft", "Qtrans");

	settings.beginGroup("QTrans");
	English_Path = settings.value("EngDic").toString();
	compactMode = settings.value("compactMode",false).toBool();
	enabled = settings.value("enabled",true).toBool();
	AutoPopUp = settings.value("AutoPopUp",true).toBool();
	DockIcon = settings.value("DockIcon",true).toBool();
	DontClose = settings.value("DontClose",true).toBool();
	StartMin = settings.value("StartMin",false).toBool();
	hideTask = settings.value("hideTask",false).toBool();
	enableShortCut = settings.value("enableShortCut",true).toBool();
	fontType = settings.value("Font").value<QFont>();

	if (hideTask)
		KWindowSystem::setState(winId(),NET::SkipTaskbar);

	stayOnTop = settings.value("stayOnTop",false).toBool();
	this->resize(settings.value("size", QSize(420, 120)).toSize());
	ShortKey = settings.value("ShortKey","CTRL+T").toString();
	closeAct = new KAction( this );
	closeAct->setText(i18n("I have been ported, too"));
	connect(closeAct, SIGNAL(triggered(bool)), this, SLOT(slot_ShortCut()));

	if (enableShortCut){
		closeAct->setGlobalShortcut( KShortcut(ShortKey),
			KAction::ActiveShortcut | KAction::DefaultShortcut 
		);
	} else {
		closeAct->setGlobalShortcut( KShortcut(),
			KAction::ActiveShortcut | KAction::DefaultShortcut 
		);
	}

	bgColor = settings.value("bgColor","#F7FCAB").toString();
	txtColor = settings.value("txtColor","#000000").toString();
	settings.endGroup();

	settings.beginGroup("Babylon");

	int i =  settings.value("number").toInt();

	QString n;
	for (int j = 0; j < i; j++) {
		n = QString::number(j);

		Dictionary *Item = new Dictionary(
			settings.value("fileName" + n).toString(),
			settings.value("Language" + n).toString(),
			settings.value("flagID"+n).toInt()
			);
		bab_dict->append(*Item);

	}

	KStandardDirs sd;
	QStringList dirsPath = sd.findDirs("data","qtrans/flags");
	//QString flagPath = "/usr/share/apps/qtrans/flags/";
	//QStringList::Iterator it = dirsPath.begin();
	QStringList::const_iterator it = dirsPath.constBegin();
	QString flagPath;
	if ( it != dirsPath.constEnd() )
		flagPath = (*it);

	QList<Dictionary>::const_iterator itr;

	for (itr = bab_dict->constBegin(); itr != bab_dict->constEnd(); ++itr) {
		actionsList.append(languageMenu->addAction(QIcon(QPixmap(flagPath+Flag[(*itr).flagID])), (*itr).Language));
	}

	settings.endGroup();
*/

}

void QTrans::writeConfig()
{
	//KConfig *Conf = kapp->sessionConfig();
	//Conf->writeEntry("EngDic",English_Path);
	//KConfig *config = KGlobal::config().data();

	// Program data
	//KConfigGroup cfg = config->group("ProgramData");
	//KConfigGroup config(KGlobal::config(), "TagGuesser");
	//config.writeEntry("EngDic",English_Path);
	//KConfigGroup *config = KGlobal::config();
	//config->writeEntry("EngDic",English_Path);

	//KConfigGroup config = KGlobal::config()->group("Group");
	//config.writeEntry("Key-ooo", 0);

	///configuration object of the application
/*	KSharedConfigPtr config;

	config = KGlobal::config();
	KConfigGroup cg( config, "General Options");
	cg.writeEntry("Geometry-ooo", size());
*/
	//KConfigGroup cg( KMessageBox_againConfig? KMessageBox_againConfig: KGlobal::config().data(), "Notification Messages_2" );
	//cg.writeEntry( dontShowAgainName, false, flags );
	//KConfigGroup cg( KGlobal::config().data(), "QTrans" );   //o
	KConfigGroup cg( KSharedConfig::openConfig(), "QTrans" );  //x

	cg.writeEntry("EngDic",English_Path);
	cg.writeEntry("compactMode",compactMode);
	cg.writeEntry("AutoPopUp",AutoPopUp);
	cg.writeEntry("DockIcon",DockIcon);
	cg.writeEntry("DontClose",DontClose);
	cg.writeEntry("MouseSelected",MouseSelected);				//ooo
	cg.writeEntry("StatusBarSelected",StatusBarSelected);			//ooo
	cg.writeEntry("EnableRecording",EnableRecording);			//ooo
	cg.writeEntry("StartMin",StartMin);
	cg.writeEntry("hideTask",hideTask);
	cg.writeEntry("enableShortCut",enableShortCut);
	cg.writeEntry("ShortKey",ShortKey);
	cg.writeEntry<QFont>("Font",fontType);
	//cg.writeEntry<QFont>("Font",characterFontType);				//ooo
	cg.writeEntry("bgColor",Out->bgColor);
	cg.writeEntry("txtColor",Out->txtColor);
	cg.writeEntry("expressionTxtColor",Out->expressionTxtColor);		//ooo
	cg.writeEntry("sentencePartTxtColor",Out->sentencePartTxtColor);	//ooo
	//cg.writeEntry("widgetStyle","doxygen");				//ooo
	cg.writeEntry("widgetStyle",widgetStyle);				//ooo
	cg.writeEntry("numberRecodings",numberRecodings);			//ooo


	//KConfigGroup cg2( KGlobal::config().data(), "Babylon" );   //o
    KConfigGroup cg2( KSharedConfig::openConfig(), "Babylon" );  //x

	cg2.writeEntry("number", bab_dict->count());

	QString number_;
	uint i_ = 0;

	QList<Dictionary>::const_iterator it_;

	for (it_ = bab_dict->constBegin(); it_ != bab_dict->constEnd(); ++it_) {
		number_ = QString::number(i_);
		cg2.writeEntry("fileName"+number_, (*it_).fileName);
		cg2.writeEntry("Language"+number_, (*it_).Language);
		cg2.writeEntry("flagID"+number_, (*it_).flagID);
		//cg2.writeEntry("Codec"+number_, (*it_).Codec);		//ooo
		//cg2.writeEntry("codecID"+number_, (*it_).codecID);		//ooo
		cg2.writeEntry("encodingDefinitionID"+number_, (*it_).encodingDefinitionID);		//ooo
		cg2.writeEntry("directionID"+number_, (*it_).directionID);	//ooo
		cg2.writeEntry("disableID"+number_, (*it_).disableID);		//ooo
		//cg2.writeEntry("encodingID"+number_, (*it_).encodingID);	//ooo
		cg2.writeEntry("encodingExpressionID"+number_, (*it_).encodingExpressionID);	//ooo
		i_++;
	}

	cg.sync();

/***************************/

/*	QSettings settings("MySoft", "Qtrans");

	settings.beginGroup("QTrans");
	settings.setValue("EngDic", English_Path);
	settings.setValue("compactMode",compactMode);
	settings.setValue("AutoPopUp",AutoPopUp);
	settings.setValue("DockIcon",DockIcon);
	settings.setValue("DontClose",DontClose);
	settings.setValue("StartMin",StartMin);
	settings.setValue("hideTask",hideTask);
	settings.setValue("enableShortCut",enableShortCut);
	settings.setValue("ShortKey",ShortKey);
	settings.setValue("Font",fontType);
	settings.setValue("bgColor",Out->bgColor);
	settings.setValue("txtColor",Out->txtColor);
	settings.endGroup();

	settings.beginGroup("Babylon");
	settings.setValue("number", bab_dict->count());

	QString number;
	uint i = 0;

	QList<Dictionary>::const_iterator it;

	for (it = bab_dict->constBegin(); it != bab_dict->constEnd(); ++it) {
		number = QString::number(i);
		settings.setValue("fileName"+number, (*it).fileName);
		settings.setValue("Language"+number, (*it).Language);
		settings.setValue("flagID"+number, (*it).flagID);
		i++;
	}
	settings.endGroup();
*/
}

/*-- Set the defaults settings if no config file is found --*/
void QTrans::Default()
{
	/*English_Path = "/usr/share/trans/babylon/English.dic";
	Lang_Path = "/usr/share/trans/babylon/Engtoita.dic";
	AutoPopUp = true;
	DockIcon = true;
	DontClose = true;
	StartMin = false;
	enableShortCut = true;
	ShortKey = "CTRL+T";
	fontType.setFamily("helvetica");
	fontType.setPointSize(11);*/
}

/*-- Convert from "string" to "QString" --*/
QString str(string s)
{
	int n=s.size();
	QString S;
	for (int i=0;i<n;i++) S[i]=s[i];
	return S;
}

/*--Convert and add a space after ';' and ','--*/
QString str_2(QString S)
{
	//QString S=str(s);
	int i=-1;
	do {
		//i = S.find(';',i+1);
		i = S.indexOf(';',i+1);   //ooo
		if (i!=-1) S.insert(i+1," ");
	} while (i!=-1);
	i=-1;
	do {
		i = S.indexOf(',',i+1);
		if (i!=-1) S.insert(i+1," ");
	} while (i!=-1);
	
	return S;
}

/*-- Truncate a string at the first space char
     and remove any non-alpha char at the begin or at
     at the end of the word              --*/
QString tr_str(QString s)
{
	QChar C;
	unsigned i;
	/*-- this is too much invasive!
		and popup too often --*/
	/*for (i=0;i<s.length();i++) {
		C=s[i];
		if (!C.isLetter()) s[i]=' ';
	}*/
	for (i = 0; i < s.length(); i++) {
		C = s[i];
		if (!C.isLetter())
			s[i] = ' ';
		else break;
	}
	for (i = s.length() - 1; i > 0; i--) {
		C = s[i];
		if (!C.isLetter())
			s[i] = ' ';
		else break;
	}
	//s = s.simplifyWhiteSpace();
	s = s.simplified();   //ooo
	//int j = s.find(' ',0);
	int j = s.indexOf(' ',0);   //ooo
	if (j>0) s.truncate(j);
	
	return s;
}

QString reverseString(QString s)
{
	QString result = "";
	for (int i=(s.length()-1); i>=0; i--) {
		result += s[i];
	}
	return result;//result;
}

//#include "utils.moc"
