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

#include "cluceneguisearch.h"
#include <kapplication.h>
#include <qlayout.h>
#include <qcheckbox.h>

//used to return query to clucene ioslave when onrequest mode ON
#include <iostream>

//used to start a new search when used in standalone mode
#include <krun.h>
#include <kservice.h>
#include <kdialog.h>
 
CLuceneGuiSearch::CLuceneGuiSearch( QWidget */*parent*/, const char */*name*/)
		: KDialogBase( 0, "searchdialog", TRUE, "Have fun",
			       KDialogBase::User1|KDialogBase::Ok|KDialogBase::Cancel|KDialogBase::Apply,
				KDialogBase::NoDefault, TRUE),
 		  m_onRequest(FALSE)
{
	
	setButtonText(KDialogBase::User1,"SaveAs");
	enableButton(KDialogBase::User1,FALSE);
	QSizePolicy qSizePolicy(QSizePolicy::MinimumExpanding,
				QSizePolicy::MinimumExpanding,FALSE);
	this->setSizePolicy(qSizePolicy);
	//main widget of the dialog
	m_page = new QWidget(this,"mainPage");

	//creates a scrollview widget in m_page widget
	m_scrollView = new CLuceneGuiSearchHelper( m_page,"scrollView");
	
	//create boolean search TODO:enable it write parser
	//m_boolField = new QueryFieldBoolean(m_page , "BoolField");
	
	//layout attached to the main widget
	l = new QVBoxLayout(m_page, 0 , -1,  "layout l");
	l->setResizeMode(QLayout::Minimum);

	label = new QLabel(m_page);
	label->setText("<b>Find documents or information:<b>");
	label->setTextFormat(Qt::RichText);
	
	//TODO: this would help integrating with a metaSearch engine.
	//where to direct the search:
	KComboBox * searchRedirection = new KComboBox(FALSE, m_page);
	searchRedirection->insertItem( tr2i18n( "with clucene" ) );
	searchRedirection->insertItem( tr2i18n( "on file system" ) );
	searchRedirection->insertItem( tr2i18n( "with locate" ) );
	searchRedirection->insertItem( tr2i18n( "on the web" ) );
	QToolTip::add(searchRedirection,"This combobox has no functionality yet"); 
// 	searchRedirection->setEnabled(FALSE);
	
	QHBoxLayout * l4 = new QHBoxLayout(l, 10, "layout l3");
	l4->addWidget(label, 3);
// 	l4->setResizeMode(QLayout::Fixed);
	l4->addWidget(searchRedirection);

	
	l->addSpacing(15);
	l->addWidget(m_scrollView);
	l->addSpacing(15);
	
	//create a "Give a name to the query"-widget and its boxlayout
	QCheckBox * label2 = new QCheckBox (m_page);
	label2->setText("Name query:");
	label2->setDown(FALSE);
	queryName= new KLineEdit(m_page);
	queryName->setEnabled(FALSE);
	connect (label2, SIGNAL(toggled(bool)) , queryName , SLOT(setEnabled(bool)));
	
	l2 = new QHBoxLayout(l,20, "layout l2");
	l2->addWidget(label2);
	l2->addSpacing(10);
	l2->addWidget(this->queryName);
	l2->setResizeMode(QLayout::Fixed);
		
	
	connect (this , SIGNAL(applyClicked()), this, SLOT(slotApply()));
	connect (this , SIGNAL(okClicked()), this, SLOT(slotOk()));
	connect (this , SIGNAL(cancelClicked()), this, SLOT(slotCancel()));
	
	QTimer::singleShot( 0, this , SLOT(initDialogGeometry()) );
	
	//change apply to send queryName
// 	this->setButtonApplyText("Send query",0,0);
}

//again very hacky...
void CLuceneGuiSearch::initDialogGeometry()
{
	kdDebug() << "CLuceneGuiSearch::initDialogGeometry CALLED geo"  << geometry() << endl;
	
	QueryField * qF = new QueryField(0, 0 , 0, "0" );
	qF->slotCreatePlugin( "Mod. Time" );
	int minimumWidth = qF->m_newWidth;
// 	int minimumHeight = qF->m_newHeight;
	
	m_scrollView->setResizePolicy(QScrollView::AutoOneFit);

	int pageHeight = m_page->size().height();
	m_page->setMinimumSize(minimumWidth, (int) ((((double)pageHeight)*1.4)));
	kdDebug() << "CLuceneGuiSearch::initDialogGeometry CALLED geom_page"  << m_page->minimumSize() << endl;

	setMainWidget(m_page);	
	updateGeometry();
	this->m_scrollView->slotAddQueryFieldBelow();
	show();
}

void CLuceneGuiSearch::slotCancel()
{
	kdDebug() << "CLuceneGuiSearch::slotCancel CALLED"  << endl;
	kapp->quit();
}

void CLuceneGuiSearch::slotOk()
{
	kdDebug() << "CLuceneGuiSearch::slotOk() CALLED"  << endl;

	sendQueryString();
	kapp->quit();
}

void CLuceneGuiSearch::onrequest(bool b)
{
	kdDebug() << "CLuceneGuiSearch::onrequest CALLED"  << b << endl;
	
	m_onRequest = b;
	if (!m_onRequest)
	{
		this->showButtonApply(TRUE);
	}
	else
	{
		this->showButtonApply(FALSE);
		//test ASYNC with apply
// 		this->showButtonApply(TRUE);
	}
}

void CLuceneGuiSearch::slotApply()
{
	sendQueryString();
}

//TODO: create a desktopfile with the saved query, to allow further editing of the query
void CLuceneGuiSearch::sendQueryString()
{
	kdDebug() << "CLuceneGuiSearch::sendQueryString CALLED"  << endl;

	QueryField * queryItem;
	QString query;
	
	for (  queryItem = m_scrollView->m_queryFieldList.first(); queryItem; 
		      queryItem= m_scrollView->m_queryFieldList.next() )
	{
		QString str = queryItem->pQF->getQuery();
		if (!str.isEmpty())
		{
			str = "(" + str + ") ";
		
			bool plus = queryItem->getPlus();
			bool minus = queryItem->getMinus();
			if ( plus && (!minus) )
			{
				str = "+" + str;
			}
			else if ( (!plus) && minus )
			{
				str = "-" + str;
			}
			else
			{
				//?????
			}
			query.append( str );
		}
	}
	
	//TODO: write a "isQueryValid() function, below are a few "random" tests
	query.stripWhiteSpace();
	query.replace("/","|");
	query.remove("**");
	query.remove("**");
	query.replace(" *"," ");
	query.replace("(*","(");
	query.replace(" ?"," ");
	query.replace("(?","(");
	query.replace("|*","|");
	query.replace("|?","|");
	query.replace("*","");
	
	query.replace("?","$");
	
	//add NAME to query String : must be parsed out by the ioslave
	QString name;
	if (this->queryName->isEnabled())
	{
		name = queryName->text();
		//TODO: isValid queryname
		if (!name.isEmpty())
			query.append("/ clQN:" + name);
		//createGUIDesktopFile();
	}
	if (m_onRequest)
	{
		kdDebug() << "CLuceneGuiSearch::sendQueryString ONREQUEST"  << query<<endl;
		std::cout <<(QCString) query ;
	}
	else
	{
		QString urlStr = IOSLAVE_PROTOCOL_NAME_FULL+query;
		KRun::runURL(urlStr,"inode/directory",FALSE,TRUE);
	}
	return;
}

//not implemented
void CLuceneGuiSearch::createGUIDesktopFile()
{
}



#include "cluceneguisearch.moc"
