/***************************************************************************
 *   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 "indexesmanagerwidget.h"

#include <qstring.h>
#include <klineedit.h>
#include <kurlrequester.h>
#include <klistbox.h>
#include <kcombobox.h>
#include <kdebug.h>
#include <qmap.h>

#include <kurlrequester.h>
#include <kurl.h>
#include <kconfig.h>
#include <kconfigbase.h>
#include <qcheckbox.h>
#include <kactionselector.h>
#include <kprocess.h>
#include <kapplication.h>
#include <dcopclient.h>

#include "helpertestsstring.h"
#include <kio/job.h>
#include <kio/netaccess.h>

#include <dcopclient.h>
#include <kclucene_indexer_daemon_dcopiface_stub.h>
#include <kapplication.h>

#include <unistd.h>   //02.06.05 Jol  sleep or QThread::sleep (protected) 


IndexesManagerWidget::IndexesManagerWidget
			(
 				KDialogBase * dialog ,
	 			Settings * settings,
  				QMap< QString ,QString > * indexMap,
  				QWidget* parent, 
				const char* name, 
				WFlags fl
			)
			: IndexManagerWidgetBase(parent,name,fl)
{
	m_dialog = dialog;
	m_settings = settings;
	m_indexMap = indexMap;
	
 	connect ( this->indexName, SIGNAL(activated(const QString &)),
 		  this, SLOT(someIndexSelected(const QString& )));
	
	connect (this->eraser, SIGNAL(clicked()) , this , SLOT(slotEraser()));
	
	connect ( this->deleteHits, SIGNAL(clicked()), this, SLOT(slotDeleteHits()));

	connect ( this->merge, SIGNAL(clicked()), this, SLOT(slotMerge()));
	
	updateEntriesInWidget( m_indexMap->begin().key() );
}

IndexesManagerWidget::~IndexesManagerWidget()
{
}

void IndexesManagerWidget::someIndexSelected(const QString & indexName)
{
	updateEntriesInWidget( "clucene_Index-" + indexName );	
}

void IndexesManagerWidget::updateEntriesInWidget(const QString & targetIndex)
{
	kdDebug() << "MainGUI::updateEntriesInWidget()" << targetIndex <<endl;

		this->indexName             -> clear();
		QStringList indexNames;
		QStringList indexNamesMerge;
		QMap<QString , QString>::Iterator it;
		
		//FIXME:use real name
		for ( it = m_indexMap->begin(); it != m_indexMap->end(); ++it )
		{
			QString name = 		it.key().mid(14,it.key().length());	 
			kdDebug() << "MainGUI::key" <<  name<<endl;
			indexNames.append(name);
			//append indexname only if it is not the target index.
			if (! (targetIndex==it.key()))
				indexNamesMerge.append(name);
	
	
		}
		this->indexName             -> insertStringList(indexNames);
		this->indexName             -> setCurrentText( targetIndex.mid(14,targetIndex.length()) );//FIXME:use stored name.
		this->toBeMergedIndex->availableListBox()->clear();	
		this->toBeMergedIndex->availableListBox()->insertStringList(indexNamesMerge);
}



void IndexesManagerWidget::slotNewIndex(const QString & newName)
{
	kdDebug() << "IndexesManagerWidget::slotNewIndex() CALLED :"<< newName <<endl;
	kdDebug() << m_indexMap->keys()<<endl;
	updateEntriesInWidget( m_indexMap->begin().key());
/*	QString name = newName.mid(14,newName.length());
	this->indexNames->selectedListBox()->insertItem(name);*/
}

//TODO: delete index not implemented yet. Deletes only targetted index config.
void IndexesManagerWidget::slotEraser()
{
	kdDebug() << "IndexesManagerWidget::slotEraser" << endl;

	QString indexEntry = "clucene_Index-" + this->indexName->currentText() ;
	QString test = m_indexMap->find(indexEntry).key();
	if (!(test==QString::null))
	{
		KConfig * cfg = m_settings->config();
		cfg->setGroup(indexEntry);
		//this entry really exists.
		QString urlStr = HelperTestsString::name2path(cfg->readEntry( "indexLocation"     ));
		
		//FIXME:user warning here with url to be deleted. and confirm
		bool ok = KIO::NetAccess::del(KURL::fromPathOrURL(urlStr)  , this );
		if (!ok)
		{
			//delete failed
			kdError() << "Delete " << urlStr <<"failed" <<endl;
		}
		cfg->deleteGroup(indexEntry , true , false);
		this->indexName->removeItem (this->indexName->currentItem());
		m_indexMap->remove(indexEntry);

		
		
		emit indexRemoved(indexEntry);
		updateEntriesInWidget( m_indexMap->begin().key());
	}
}

//TODO:not implemented yet. cl_util 
void IndexesManagerWidget::slotDeleteHits()
{
	QString query('"' + this->query->text() + '"');
	kdDebug() << "IndexesManagerWidget::slotDeleteHits() query :"<< query <<endl;
	QString indexAbsPath;
	
	kdDebug() << "IndexesManagerWidget::slotDeleteHits() path :"<< indexAbsPath <<endl;

	//dcop->deleteHits(query , indexPath);
	KConfig * cfg = m_settings->config();

	KCLuceneIndexerDaemonDCOPIface_stub iface("kclucene-indexer-daemon" , "KCLuceneIndexerDaemon");
	/*int valid = */iface.deleteHits(
			kapp->dcopClient()->appId(),
	HelperTestsString::name2path(cfg->readEntry    	( "indexName"         )),
	HelperTestsString::name2path(cfg->readEntry    	( "indexLocation"     )),
	query
				    );
}

//TODO:not implemented yet. cl_util 
void IndexesManagerWidget::slotMerge()
{
	QStringList toMergeIndexAbsPathList;
	QString targetIndexAbsPath;
	//dcop->merge(query , indexPath);
}


bool IndexesManagerWidget::wakeDCOP()
{
	int counter = -1;
	// call and wake up the indexer daemon service 
	kdDebug() << "Start wake up"<< endl;
	if (!DCOPClient::mainClient()->isApplicationRegistered("kclucene-indexer-daemon")) 
	{
		QString error;
		fprintf(stderr, "I have to wake you up\n");
		if (!(KApplication::startServiceByDesktopName("kclucene_indexer_daemon", QStringList(),
		      &error , 0  , 0 , 0, TRUE) == 0))
		{
			fprintf(stderr, "Starting cLuceneDcopIndexerDaemon failed with message " +
					error +"\n" );
			return FALSE;  //bad
		}
		else
		{
			fprintf(stderr, "Good I did it \n");
			while (counter < 5)
			{
				counter++;
				sleep(counter);	
				if (DCOPClient::mainClient()
						->isApplicationRegistered
						("kclucene-indexer-daemon")) 
				{
						return TRUE;
				}
			}
			fprintf(stderr, "Hum I did start something, but cannot find its dcop intrerface \n");
			return FALSE;
		}
	}
	else
	{
		fprintf(stderr, "You are already running !!!\n");
	}
	return TRUE;  //good
}

#include "indexesmanagerwidget.moc"

