/***************************************************************************
 *   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        *
 *   MERCHANTABLITY 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 <klocale.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kcombobox.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qmap.h>
#include <kurlrequester.h>
#include <kurl.h>
#include <kconfig.h>
#include <kconfigbase.h>
#include <qcheckbox.h>

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

#include <dcopclient.h>

#include <qlayout.h>
#include <kdialogbase.h>
#include <qpixmap.h>
#include <kiconloader.h>
#include <kguiitem.h>

#include "maingui.h"

//FIXME:press return on index Name should not be visible if not apply
MainGUI::MainGUI(displayType display) : QWidget()
{
	//init kconfigskeleton
	m_settings = Settings::self();
	loadIndexAndTextConvertersNames();
	
	//init new dialog
	m_dialog = new KDialogBase
			(
				KConfigDialog::IconList, 
				KDialogBase::WStyle_DialogBorder,
				this,
				"kclucene-indexer-config",
				TRUE,
				"caption",
				KDialogBase::Ok|KDialogBase::Apply,
				KDialogBase::NoDefault,
				TRUE
			 );
	//modify apply button		
	m_dialog->setButtonGuiItem 
			(
				KDialogBase::Apply,KGuiItem
					(
				        	"Save changes",
						"save_all",
						"saves changes",
						QString::null
					) 
			);
	//modify Ok/Quit button
	m_dialog->setButtonGuiItem 
			(
				KDialogBase::Ok,KGuiItem
				(
					"Quit",
					"exit",
					"",
					QString::null
				)
			);
		

			
	//page config used to create or update indexes
	QVBox *pageCreateIndex = m_dialog->addVBoxPage( i18n("Create Index"),
			QString::null,  SmallIcon("vcs_add",32) );
	
	//page config used to setup text converters for full content indexing
	QVBox *pageTextConverter = m_dialog->addVBoxPage( i18n("Content converters"), QString::null,  SmallIcon("filter",32) );
	
	//init text-convertors config before index-creators, because existing convertors
	//are shown in the index-creator page
	m_textConvertor = new TextConverterWidget( m_dialog , m_settings,
			 &m_textConvertersNameMap , (QWidget*) pageTextConverter,
			 "TextConverter",0 ); 
		
	m_indexCreator = new IndexerWidget(m_dialog, m_settings, &m_indexMap,
			&m_textConvertersNameMap, (QWidget*) pageCreateIndex, 
			"Adddatabases ",0 ); 
			
	//page used to merge existing indexes or remove entries from indexes
	QVBox *pageIndexManager = m_dialog->addVBoxPage( i18n("Manage Indexes"),
			 QString::null,  SmallIcon("vcs_status",32) );
	
	m_indexManager = new IndexesManagerWidget( m_dialog , m_settings , &m_indexMap ,
			(QWidget*) pageIndexManager, "ManageDatabases" ); 
	
	//page used to setup the ioslave default index-configuration.
	QVBox *pageSearchConfig= m_dialog->addVBoxPage( i18n("Search configure"), QString::null,  SmallIcon("favorites", 32) );
	
	m_ioslaveConfig = new IOSlaveConfigWidget( m_dialog , m_settings , &m_indexMap ,
			(QWidget*) pageSearchConfig, "IOSlave Config" ); 
			
	connect (this	         , SIGNAL(indexCreatorCalled	   (	)), 
		 m_indexCreator  , SLOT  (saveSettingsIndexCreator  (	)));
	connect (this            , SIGNAL(indexManagerCalled	   (	)), 
		 m_indexManager  , SLOT  (saveSettingsIndexManager   (	)));
	connect (this            , SIGNAL(textConverterCalled	   (	)), 
		 m_textConvertor , SLOT  (saveSettingsTextConvertor (	)));
	connect (this            , SIGNAL(ioSlaveConfigCalled	   (	)), 
		 m_ioslaveConfig , SLOT  (saveSettingsIOSlave	   (	)));
		
	connect (m_indexCreator  , SIGNAL(newIndex	(const QString& )),
		 m_ioslaveConfig , SLOT  (slotNewIndex	(const QString&)));
	connect (m_indexCreator  , SIGNAL(newIndex	(const QString& )),
		 m_indexManager  , SLOT  (slotNewIndex	(const QString&)));
	connect (m_indexManager  , SIGNAL(indexRemoved	(const QString& )),
		 m_ioslaveConfig , SLOT  (slotRemoveIndex(const QString&)));
	connect (m_indexManager  , SIGNAL(indexRemoved	(const QString& )), 
		 m_indexCreator  , SLOT  (slotRemoveIndex(const QString&)));
		
	connect ( m_textConvertor      , SIGNAL(newTextConverter	 (const QString& )) ,
		  m_indexCreator       , SLOT  (slotNewTextConverter	 (const QString&)));
	connect ( m_textConvertor      , SIGNAL(textConverterRemoved     (const QString& )),
		  m_indexCreator       , SLOT  (slotRemoveTextConverter  (const QString& )));
	connect ( m_dialog             , SIGNAL(aboutToShowPage   	 (QWidget * 	 )), 
		  this                 , SLOT  (setUpPages		 (QWidget* 	 )));
	connect (m_indexCreator->setup , SIGNAL(clicked		 	 (	         )), 
		 this                  , SLOT  (slotSetupTextConverters  (               )));
		
	switch( display ) 
	{
		//app started standalone
		case ALL :
		{
			m_dialog->showPage(0);
			setUpPages((QWidget*) pageCreateIndex);
			break;	
		}
		//app started from ioslave
		case IOSLAVE_ONLY:
		{
			m_dialog->showPage(3);
			break;			
		}
	}
	
	connect (m_dialog, SIGNAL(applyClicked()) , this , SLOT(saveSettings()));
	connect (m_dialog, SIGNAL(okClicked())    , this , SLOT(slotQuit    ()));
	connect (m_dialog, SIGNAL(finished())     , this , SLOT(slotQuit    ()));
	
	//show dialog
	m_dialog -> show();
	
	kdDebug() << "INIT" << m_settings->config()->groupList() << endl;
}


MainGUI::~MainGUI()
{
}

void MainGUI::slotSetupTextConverters()
{
	m_dialog->showPage(1); 
}
void MainGUI::saveSettings()
{
	int active = m_dialog->activePageIndex();
	
	kdDebug() << "MainGUI::saveSettings() CALLED" <<  QString::number(active) << endl;
	
	if ( active == 0 )
	{	
		emit indexCreatorCalled();
	}	
	else if (active  == 1 )
	{
		emit textConverterCalled();
	}
	else if (active  == 2 )
	{
		emit indexManagerCalled();
	}
	else if (active  == 3 )
	{
		emit ioSlaveConfigCalled();
	}
	

}

void MainGUI::slotQuit()
{
	kapp->quit();
}


void MainGUI::setUpPages(QWidget * /*page*/)
{
	int active = m_dialog->activePageIndex();
	
	kdDebug() << "MainGUI::saveSettings() CALLED" <<  QString::number(active) << endl;
	
	if ( active == 0 )
	{	
		m_dialog->enableButton(KDialogBase::User1 , FALSE);
		m_dialog->showButton(KDialogBase::Apply , TRUE);
	}	
	else if (active  == 1 )
	{
		m_dialog->enableButton(KDialogBase::User1 , FALSE);
		m_dialog->showButton(KDialogBase::Apply , TRUE);
	}
	else if (active  == 2 )
	{
		m_dialog->showButton(KDialogBase::Apply , FALSE);
	}
	else if (active  == 3 )
	{
		m_dialog->enableButton(KDialogBase::User1 , FALSE);
		m_dialog->showButton(KDialogBase::Apply , TRUE);
	}
}


//reads the list of existing index configurations and index locations
//I am using a qmap sometimes but with no reason ;-)
void MainGUI::loadIndexAndTextConvertersNames()
{
	//all new index config starts with clucene_Index
	QStringList allGroups =  m_settings->config()->groupList();
	kdDebug() << "MainGUI::loadIndexAndTextConvertersNames()" << allGroups<< endl;

	for ( QStringList::Iterator it = allGroups.begin(); it != allGroups.end(); ++it )
	{
		QString groupName = *it;
		if ( groupName.startsWith("clucene_Index" , TRUE) )
		{
			m_settings->setCurrentGroup( groupName );
			if (!m_settings->indexLocation())
			{
				kdDebug() << "MainGUI::loadIndexAndTextConvertersNames()() ERROR IN FILE CONFIG" << endl;
				//FIXME:delete the group with error !! or mark it as error
// 				m_settings->config()->deleteGroup ( groupName,TRUE,FALSE ); 
			}
			else 
			{
				m_indexMap.insert ( groupName , m_settings->indexLocation() );
			}
		}
		else if ( groupName.startsWith("cl_Converters" , TRUE) )
		{
			m_textConvertersNameMap.insert ( groupName,"useless");
			kdDebug() << "MainGUI::loadIndexAndTextConvertersNames()() FOUND CONV GROUP" << *it << endl;
		}
	}
}

#include "maingui.moc"
