/***************************************************************************
 *   Copyright (C) 2005 by xavier helluy                                   *
 *   xavier.helluy@web.de                                                  *
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 *   This program 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 this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Steet, Fifth Floor, Boston, MA 02110-1301, USA.             *
 ***************************************************************************/
#include "helpertestsstring.h"

#include <qcheckbox.h>
#include <qradiobutton.h>
#include <klineedit.h>
#include <kurlrequester.h>
#include <klistbox.h>
#include <kcombobox.h>
#include <kdebug.h>
#include <qmap.h>
#include <klocale.h>
#include <qstringlist.h>
//TODO  $$i|$$pattern|text make local cp to a tmp dir if outputfile can't be controlled
 
#include "textconverterwidget.h"

TextConverterWidget::TextConverterWidget( KDialogBase * dialog ,
 Settings * settings,
 QMap< QString ,QString > * textConvertersNameMap,
 QWidget* parent, const char* name, WFlags fl)
: TextConverterWidgetBase(parent,name,fl)
{
	m_dialog = dialog;
	m_settings = settings;
	m_textConvertersNameMap = textConvertersNameMap;
	
	connect (this->removeMime,  SIGNAL(clicked()) , this , SLOT(slotRemoveMime()));
	connect (this->removePattern,  SIGNAL(clicked()) , this , SLOT(slotRemovePattern()));
	
	connect (this , SIGNAL(MimeOrPattern()) , this , SLOT(slotMimeOrPattern()));
	connect (this->mimetype , SIGNAL(clicked()) , this , SLOT(slotMimeOrPattern()));
	connect (this->pattern , SIGNAL(clicked()) , this , SLOT(slotMimeOrPattern()));
	connect (this->mimetypeList , SIGNAL(activated(int)) , this , SLOT(slotMimeOrPattern()));
	connect (this->patternList , SIGNAL(activated(int)) , this , SLOT(slotMimeOrPattern()));
	connect ( this->textConvertersName, SIGNAL(activated(const QString &)), this, SLOT(someIndexSelected(const QString &)));
	
	
// 	connect (this->textConverters)
	connect (this->removeTextConvertersName, SIGNAL(clicked()) , this , SLOT(slotRemoveTextConvertersName()));
	
	this->mimetypeList->setDuplicatesEnabled(FALSE);
	this->patternList->setDuplicatesEnabled(FALSE);
	updateEntriesInWidget(m_textConvertersNameMap->begin().key());
	
	
	
// 	connect (this->eraser, SIGNAL(clicked()) , this , SLOT(slotEraser()));
	// 
	// 
// 	updateEntriesInWidget( m_indexMap.begin().key() );
}

TextConverterWidget::~TextConverterWidget()
{
}


void TextConverterWidget::someIndexSelected(const QString & itemStr)
{
	kdDebug() << "TextConverterWidget::someIndexSelected() CALLED" <<  itemStr << endl;
	
// 	QString groupName;
// 	groupName = "cl_Converters-" + itemStr;


	//reset m_indexMap
	//check if it is a new entry
	QMap<QString , QString>::Iterator it = m_textConvertersNameMap->find("cl_Converters-"+itemStr);
	
	if ( it == m_textConvertersNameMap->end())
	{
		kdDebug() << "TextConverterWidget::someIndexSelected() NEW ENTRY" <<  itemStr << endl;

		//new entry found
		//check it is "clean":
		if (itemStr.isEmpty())
		{
			//name is not clean
			this->textConvertersName->removeItem (this->textConvertersName->currentItem());	
		}
		else
		{
			//name is new and is clean
			
			//remove the item from the combobox because apply is not here yet
			this->textConvertersName->removeItem (this->textConvertersName->currentItem());
			this->textConvertersName->setEditText(itemStr);
			
			//clean up a bit
			this->proc->clear();
			this->args->clear();
			this->output->clear();
			//that's it
		}
	}
	else
	{
		//this is an already existing entry
		//read the group and update the gui.
		
		//create a group name
		QString groupName = "cl_Converters-" + itemStr;
		
		//check group is valid
		bool validEntries = validateStoredIndexEntries(groupName);
		
		//update the widget
		if (!validEntries)
		{
			//FIXME:create defaults entries
		}
		else
		{
			//stored entries are valid:
			//update the widget:
			updateEntriesInWidget( groupName );
		}			
	}
}
	
//TODO:loadsettings : get the stored settings correesponding to the selected name.
void TextConverterWidget::saveSettingsTextConvertor()
{
	kdDebug() << "TextConverterWidget::saveSettingsTextConvertor() CALLED" << endl;

	//check if name already exists 
	QString conv = this->textConvertersName->currentText(); 
	QString groupName = "cl_Converters-" + conv;
	QString res = m_textConvertersNameMap->find(groupName).key();
	if (!(res==QString::null))
	{
		kdDebug() << "TextConverterWidget::saveSettingsTextConvertor EXISTS ALREADY" << endl;
		storeEntries(groupName);
	}
	else
	{
		kdDebug() << "TextConverterWidget::saveSettingsTextConvertor  NEW GROUP" << endl;
		if (HelperTestsString::isValidFileName(conv))
		{
			m_textConvertersNameMap->insert ( groupName ,"useless" );
			storeEntries(groupName);
			emit newTextConverter(groupName );
		}
		
	}
	//?????????
	m_settings->config()->sync();
	//see if it updates the list of mime and patterns
	updateEntriesInWidget(groupName);
	
}

void TextConverterWidget::storeEntries( QString & convGroup )
{
	kdDebug() << "TextConverterWidget::storeEntries()" <<  convGroup << endl;
	KConfig * cfg = m_settings->config();

	cfg->setGroup(convGroup);
	
	cfg->writeEntry( "pattern" , 		this->pattern->isChecked());
	cfg->writeEntry( "mimetype", 		this->mimetype->isChecked());
	cfg->writeEntry( "text", 		this->text->isChecked());
	cfg->writeEntry( "html", 		this->text->isChecked());
	cfg->writeEntry( "xml", 		this->text->isChecked());
		
	bool isMime = this->mimetype->isChecked();
	QString mymimetype = this->mimetypeList->currentText();
	QString mypattern = this->patternList->currentText();
	QString myproc = this->proc->text();
	QString myargs = this->args->text();
	QString myoutput = this->output->text();
	if (isMime)
	{
		//TODO: check if valid  mimetype
		
		
		//add entry to the mimelist if valid and if mime name there
		if  ((!mymimetype.isEmpty()) 
				     && (!myproc.isEmpty()) 
				     && (!myargs.isEmpty() ) )
		{
			if (myoutput.isEmpty())
				myoutput = "empty";
			QStringList entry;
			entry <<myproc << myargs<<myoutput;
			
			//check if already stored. delete old entries
			int  id = m_mimeList.findIndex(mymimetype);
			kdDebug() << "TextConverterWidget::storeEntries()REPLACE ENTRY"   << endl;

			if (!(id==-1))
			{
				//found a record. removes it now
				m_mimeList.remove(m_mimeList.at(id));
				m_mimeProc.remove(m_mimeProc.at(id));
				m_mimeArgs.remove(m_mimeArgs.at(id));
				m_mimeOutput.remove(m_mimeOutput.at(id));
			}
			//new entry
				m_mimeList.append(mymimetype);
				m_mimeProc.append(myproc);
				m_mimeArgs.append(myargs);
				m_mimeOutput.append(myoutput);
			
			
			cfg->writeEntry("MimeList" , m_mimeList);
			cfg->writeEntry("MimeProc" , m_mimeProc);
			cfg->writeEntry("MimeArgs" , m_mimeArgs);
			cfg->writeEntry("MimeOutput" , m_mimeOutput);
		}
		//check if there is at least one entry
		else if (this->mimetypeList->count()==0)
		{
			cfg->writeEntry("MimeList" , "");
			cfg->writeEntry("MimeProc" , "");
			cfg->writeEntry("MimeArgs" , "");
			cfg->writeEntry("MimeOutput" , "");

			//no items
			return;
		}
		else
		{
			return;
		}
	}
	else
	{
		//add entry to the pattern list
		//TODO: check if valid  mimetype
		
		//add entry to the mimelist if valid
		if  ((!mypattern.isEmpty())  && (!myproc.isEmpty()) && (!myargs.isEmpty() ) )
		{
			if (myoutput.isEmpty())
				myoutput = "empty";
			QStringList entry;
			entry <<myproc << myargs<<myoutput;
			
			//check if already stored. delete old entries
			int id= m_patternList.findIndex(mypattern);
			if (!(id==-1))
			{
				//found a record. removes it now
				m_patternList.remove(m_patternList.at(id));
				m_patternProc.remove(m_patternProc.at(id));
				m_patternArgs.remove(m_patternArgs.at(id));
				m_patternOutput.remove(m_patternOutput.at(id));
			}
			//new entry
			m_patternList.append(mypattern);
			m_patternProc.append(myproc);
			m_patternArgs.append(myargs);
			m_patternOutput.append(myoutput);
			
			cfg->writeEntry("PatternList" , m_patternList);
			cfg->writeEntry("PatternProc" , m_patternProc);
			cfg->writeEntry("PatternArgs" , m_patternArgs);
			cfg->writeEntry("PatternOutput" , m_patternOutput);
		}
		//check if there is at least one entry
		else if (this->patternList->count()==0)
		{
			cfg->writeEntry("PatternList" , "");
			cfg->writeEntry("PatternProc" , "");
			cfg->writeEntry("PatternArgs" , "");
			cfg->writeEntry("PatternOutput" , "");

			//no items
			return;
		}
		else
		{
			return;
		}

	}
}

void TextConverterWidget::slotRemoveTextConvertersName()
{
	QString entry = "cl_Converters-" + this->textConvertersName->currentText() ;
	//FIXME: not quite il18n
// 	if (!(entry == "cl_Converters-Default setup"))
// 	{
	QString test = m_textConvertersNameMap->find(entry).key();
	if (!(test==QString::null))
	{
		KConfig * cfg = m_settings->config();
		cfg->deleteGroup(entry , true , false);
		this->textConvertersName->removeItem (this->textConvertersName->currentItem());
		m_textConvertersNameMap->remove(entry);
		kdDebug() << "INDEX REMOVED SIGNAL " << endl;
		updateEntriesInWidget( m_textConvertersNameMap->begin().key());
		//simple entry emitted
		emit textConverterRemoved(entry);
	}
// 	}
}


void TextConverterWidget::slotRemoveMime()
{
	QString entry = this->mimetypeList->currentText();
	int id = m_mimeList.findIndex(entry);
	kdDebug() << "REMOVE mime:id " <<  id << " count-1:" << m_mimeList.count()-1 <<endl;
	kdDebug() << "REMOVE mime:id " <<  id << " count-1:" << m_mimeProc.count()-1 <<endl;
	kdDebug() << "REMOVE mime:id " <<  id << " count-1:" << m_mimeArgs.count()-1 <<endl;
	kdDebug() << "REMOVE mime:id " <<  id << " count-1:" << m_mimeOutput.count()-1 <<endl;
	kdDebug() << "REMOVE combo   " <<  id << " count-1:" << mimetypeList->count()-1 <<endl;

	
	if ((id==-1))
	{
		
		this->mimetypeList->clear();
	}
	else
	{
		//found a record. removes it now
		m_mimeList.remove(m_mimeList.at(id));
		m_mimeProc.remove(m_mimeProc.at(id));
		m_mimeArgs.remove(m_mimeArgs.at(id));
		m_mimeOutput.remove(m_mimeOutput.at(id));
		kdDebug() << "REMOVE combo current  " <<  mimetypeList->currentItem() << " count-1:" << mimetypeList->count()-1 <<endl;

		this->mimetypeList->removeItem(this->mimetypeList->currentItem());
		if (this->mimetypeList->currentItem()==this->mimetypeList->count())
		{
			kdDebug() << "REMOVE combo  id-1  " <<  id << " count-1:" << mimetypeList->count()-1 <<endl;

			this->mimetypeList->setCurrentItem(id-1);
		}
// 		updateEntriesInWidget("Converters" + this->indexName->currentText());
	}
}

void TextConverterWidget::slotRemovePattern()
{

	QString entry = this->patternList->currentText();
	int id = m_patternList.findIndex(entry);
	if ((id==-1))
	{
		this->patternList->clear();
	}
	else
	{
		//found a record. removes it now
		m_patternList.remove(m_patternList.at(id));
		m_patternProc.remove(m_patternProc.at(id));
		m_patternArgs.remove(m_patternArgs.at(id));
		m_patternOutput.remove(m_patternOutput.at(id));
		this->patternList->removeItem(this->patternList->currentItem());
		this->mimetypeList->removeItem(this->mimetypeList->currentItem());
		if (this->patternList->currentItem()==this->patternList->count())
		{
			kdDebug() << "REMOVE combo  id-1  " <<  id << " count-1:" << patternList->count()-1 <<endl;

			this->patternList->setCurrentItem(id-1);
		}


	}

}


void TextConverterWidget::updateEntriesInWidget(const QString & group)
{
	kdDebug() << "TextConverterWidget::updateEntriesInWidget()" << group <<endl;

	//FIXME:hack. when update is called the first time with an empty string
	QString currentName;
	QString groupName;
	KConfig * cfg = m_settings->config();
	
	if (group.isEmpty())
	{
		groupName="cl_Converters-Default";
		currentName = "Default";
		cfg->setGroup(groupName);
		storeEntries(groupName);
		emit newTextConverter(groupName );

		

	}
	else
	{
		groupName = group;
		cfg->setGroup(groupName);
		currentName = this->textConvertersName->currentText();
	}
	
	
	//update list of indexes
	
	QMap<QString , QString>::Iterator it;
	this->textConvertersName -> clear();
	QStringList names;
	
// 	names.append(i18n("all indexes"));
// 	names.append("Default setup");
	
	for ( it = m_textConvertersNameMap->begin(); it != m_textConvertersNameMap->end(); ++it )
	{
		QString name = it.key().mid(14,it.key().length());	 
		names.append(name);
	}
	this->textConvertersName             -> insertStringList	(names);
	if (!currentName.isEmpty())
		this->textConvertersName		-> setCurrentText	( currentName );
	
	m_patternList 			=	cfg->readListEntry( "PatternList");
	m_patternProc			=	cfg->readListEntry( "PatternProc");
	m_patternArgs			=	cfg->readListEntry( "PatternArgs");
	m_patternOutput			=	cfg->readListEntry( "PatternOutput");
		
	m_mimeList			=	cfg->readListEntry( "MimeList");
	m_mimeProc			=	cfg->readListEntry( "MimeProc");
	m_mimeArgs			=	cfg->readListEntry( "MimeArgs");
	m_mimeOutput			=	cfg->readListEntry( "MimeOutput");

	
	QString currentMime = this->mimetypeList->currentText();
	QString currentPattern = this->patternList->currentText();
	this->mimetypeList->clear();
	this->patternList->clear();

	this->mimetypeList->insertStringList(m_mimeList);
	this->patternList->insertStringList(m_patternList);
	
	this->text->setChecked(cfg->readBoolEntry( "text"));
	this->html->setChecked(cfg->readBoolEntry( "html"));
	this->xml->setChecked(cfg->readBoolEntry( "xml"));


	
// 	if (! (thimimeList.findIndex(currentMime)==-1) )
// 		this->mimetypeList->setCurrentText(currentMime);
// 	if (!(m_patternList.findIndex(currentPattern)==-1))
// 		this->patternList->setCurrentText(currentPattern);
	emit MimeOrPattern();
	 
}

void TextConverterWidget::slotMimeOrPattern()
{
	
	if (this->mimetype->isChecked())
	{
		//mime is ON
		//FIXME:checkk index is never bigger than the lists
		QString currentMime = this->mimetypeList->currentText();
		int id = m_mimeList.findIndex(currentMime);
		if (! (id==-1))
		{
			this->proc->setText(m_mimeProc[id]);
			this->args->setText(m_mimeArgs[id]);
			this->output->setText(m_mimeOutput[id]);
		}
	}
	else
	{
		//FIXME:checkk index is never bigger than the lists
		//pattern is ON
		QString currentPattern = this->patternList->currentText();
		int id = m_patternList.findIndex(currentPattern);
		if (! (id==-1))
		{
			this->proc->setText(m_patternProc[id]);
			this->args->setText(m_patternArgs[id]);
			this->output->setText(m_patternOutput[id]);
		}

	}
			
}

// ???????????
bool TextConverterWidget::validateStoredIndexEntries( const QString & /*indexGroup*/)
{
	//TODO:check valid	
	return TRUE;
}




/*$SPECIALIZATION$*/


#include "textconverterwidget.moc"

