/***************************************************************************
*   Copyright (C) 2003 by                                                 *
*   Unai Garro (ugarro@users.sourceforge.net)                             *
*   Cyril Bosselut (bosselut@b1project.com)                               *
*   Jason Kivlighn (jkivlighn@gmail.com)                                  *
*                                                                         *
*   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.                                   *
***************************************************************************/

#include "selectrecipedialog.h"

#include <tqsignalmapper.h>
#include <tqtabwidget.h>
#include <tqtooltip.h>

#include <tdelocale.h>
#include <kdebug.h>
#include <tdeapplication.h>
#include <kprogress.h>
#include <tdemessagebox.h>
#include <tdeglobal.h>
#include <tdeconfig.h>
#include <kcursor.h>
#include <kiconloader.h>

#include "advancedsearchdialog.h"
#include "datablocks/categorytree.h"
#include "backends/recipedb.h"
#include "datablocks/recipe.h"
#include "selectunitdialog.h"
#include "createelementdialog.h"
#include "recipefilter.h"
#include "widgets/recipelistview.h"
#include "widgets/categorylistview.h"
#include "widgets/categorycombobox.h"

SelectRecipeDialog::SelectRecipeDialog( TQWidget *parent, RecipeDB* db )
		: TQWidget( parent )
{
	//Store pointer to Recipe Database
	database = db;

	TQVBoxLayout *tabLayout = new TQVBoxLayout( this );
	tabWidget = new TQTabWidget( this );
	tabWidget->setSizePolicy( TQSizePolicy( TQSizePolicy::MinimumExpanding, TQSizePolicy::MinimumExpanding ) );
	tabLayout->addWidget( tabWidget );

	basicSearchTab = new TQGroupBox( this );
	basicSearchTab->setFrameStyle( TQFrame::NoFrame );
	basicSearchTab->setSizePolicy( TQSizePolicy( TQSizePolicy::MinimumExpanding, TQSizePolicy::MinimumExpanding ) );

	//Design dialog

	layout = new TQGridLayout( basicSearchTab, 1, 1, 0, 0 );

	// Border Spacers
	TQSpacerItem* spacer_left = new TQSpacerItem( 10, 10, TQSizePolicy::Fixed, TQSizePolicy::Minimum );
	layout->addMultiCell( spacer_left, 1, 4, 0, 0 );
	TQSpacerItem* spacer_top = new TQSpacerItem( 10, 10, TQSizePolicy::Minimum, TQSizePolicy::Fixed );
	layout->addMultiCell( spacer_top, 0, 0, 1, 4 );

	searchBar = new TQHBox( basicSearchTab );
	searchBar->setSpacing( 7 );
	layout->addWidget( searchBar, 1, 1 );

	TDEIconLoader *il = new TDEIconLoader;
	TQPushButton *clearSearchButton = new TQPushButton( searchBar );
	clearSearchButton->setPixmap( il->loadIcon( "locationbar_erase", TDEIcon::NoGroup, 16 ) );

	searchLabel = new TQLabel( searchBar );
	searchLabel->setText( i18n( "Search:" ) );
	searchLabel->setFixedWidth( searchLabel->fontMetrics().width( i18n( "Search:" ) ) + 5 );
	searchBox = new KLineEdit( searchBar );

	TQSpacerItem* searchSpacer = new TQSpacerItem( 10, 10, TQSizePolicy::Fixed, TQSizePolicy::Minimum );
	layout->addItem( searchSpacer, 1, 2 );
	
	#ifdef ENABLE_SLOW
	categoryBox = new CategoryComboBox( basicSearchTab, database );
	layout->addWidget( categoryBox, 1, 3 );
	#endif

	TQSpacerItem* spacerFromSearchBar = new TQSpacerItem( 10, 10, TQSizePolicy::Minimum, TQSizePolicy::Fixed );
	layout->addItem( spacerFromSearchBar, 2, 1 );

	recipeListView = new RecipeListView( basicSearchTab, database );
	recipeListView->reload();
	recipeListView->setSizePolicy( TQSizePolicy::Ignored, TQSizePolicy::Expanding );
	layout->addMultiCellWidget( recipeListView, 3, 3, 1, 3 );

	buttonBar = new TQHBox( basicSearchTab );
	layout->addMultiCellWidget( buttonBar, 4, 4, 1, 3 );

	openButton = new TQPushButton( buttonBar );
	openButton->setText( i18n( "Open Recipe(s)" ) );
	openButton->setDisabled( true );
	TQPixmap pm = il->loadIcon( "ok", TDEIcon::NoGroup, 16 );
	openButton->setIconSet( pm );
	editButton = new TQPushButton( buttonBar );
	editButton->setText( i18n( "Edit Recipe" ) );
	editButton->setDisabled( true );
	pm = il->loadIcon( "edit", TDEIcon::NoGroup, 16 );
	editButton->setIconSet( pm );
	removeButton = new TQPushButton( buttonBar );
	removeButton->setText( i18n( "Delete" ) );
	removeButton->setDisabled( true );
	removeButton->setMaximumWidth( 100 );
	pm = il->loadIcon( "editshred", TDEIcon::NoGroup, 16 );
	removeButton->setIconSet( pm );

	tabWidget->insertTab( basicSearchTab, i18n( "Basic" ) );

	advancedSearch = new AdvancedSearchDialog( this, database );
	tabWidget->insertTab( advancedSearch, i18n( "Advanced" ) );

	TQToolTip::add( clearSearchButton, i18n( "Clear search" ) );

	//Takes care of all recipe actions and provides a popup menu to 'recipeListView'
	actionHandler = new RecipeActionsHandler( recipeListView, database );

	recipeFilter = new RecipeFilter( recipeListView );

	// Signals & Slots

	connect( openButton, TQ_SIGNAL( clicked() ), actionHandler, TQ_SLOT( open() ) );
	connect( this, TQ_SIGNAL( recipeSelected( bool ) ), openButton, TQ_SLOT( setEnabled( bool ) ) );
	connect( editButton, TQ_SIGNAL( clicked() ), actionHandler, TQ_SLOT( edit() ) );
	connect( this, TQ_SIGNAL( recipeSelected( bool ) ), editButton, TQ_SLOT( setEnabled( bool ) ) );
	connect( removeButton, TQ_SIGNAL( clicked() ), actionHandler, TQ_SLOT( remove() ) );
	connect( this, TQ_SIGNAL( recipeSelected( bool ) ), removeButton, TQ_SLOT( setEnabled( bool ) ) );

	connect( clearSearchButton, TQ_SIGNAL( clicked() ), this, TQ_SLOT( clearSearch() ) );

	TDEConfig * config = tdeApp->config();
	config->setGroup( "Performance" );
	if ( config->readBoolEntry("SearchAsYouType",true) ) {
		connect( searchBox, TQ_SIGNAL( returnPressed( const TQString& ) ), recipeFilter, TQ_SLOT( filter( const TQString& ) ) );
		connect( searchBox, TQ_SIGNAL( textChanged( const TQString& ) ), this, TQ_SLOT( ensurePopulated() ) );
		connect( searchBox, TQ_SIGNAL( textChanged( const TQString& ) ), recipeFilter, TQ_SLOT( filter( const TQString& ) ) );
	}
	else {
		connect( searchBox, TQ_SIGNAL( returnPressed( const TQString& ) ), this, TQ_SLOT( ensurePopulated() ) );
		connect( searchBox, TQ_SIGNAL( returnPressed( const TQString& ) ), recipeFilter, TQ_SLOT( filter( const TQString& ) ) );
	}

	connect( recipeListView, TQ_SIGNAL( selectionChanged() ), this, TQ_SLOT( haveSelectedItems() ) );
	#ifdef ENABLE_SLOW
	connect( recipeListView, TQ_SIGNAL( nextGroupLoaded() ), categoryBox, TQ_SLOT( loadNextGroup() ) );
	connect( recipeListView, TQ_SIGNAL( prevGroupLoaded() ), categoryBox, TQ_SLOT( loadPrevGroup() ) );
	connect( categoryBox, TQ_SIGNAL( activated( int ) ), this, TQ_SLOT( filterComboCategory( int ) ) );
	#endif
	connect( recipeListView, TQ_SIGNAL( nextGroupLoaded() ), TQ_SLOT( refilter() ) );
	connect( recipeListView, TQ_SIGNAL( prevGroupLoaded() ), TQ_SLOT( refilter() ) );

	connect( advancedSearch, TQ_SIGNAL( recipeSelected( int, int ) ), TQ_SIGNAL( recipeSelected( int, int ) ) );
	connect( advancedSearch, TQ_SIGNAL( recipesSelected( const TQValueList<int> &, int ) ), TQ_SIGNAL( recipesSelected( const TQValueList<int> &, int ) ) );

	connect( actionHandler, TQ_SIGNAL( recipeSelected( int, int ) ), TQ_SIGNAL( recipeSelected( int, int ) ) );
	connect( actionHandler, TQ_SIGNAL( recipesSelected( const TQValueList<int> &, int ) ), TQ_SIGNAL( recipesSelected( const TQValueList<int> &, int ) ) );

	delete il;
}

SelectRecipeDialog::~SelectRecipeDialog()
{
	delete recipeFilter;
}

void SelectRecipeDialog::clearSearch()
{
	searchBox->setText( TQString::null );
	recipeFilter->filter( TQString::null );
}

void SelectRecipeDialog::reload( ReloadFlags flag )
{
	recipeListView->reload(flag);

	#ifdef ENABLE_SLOW
	categoryBox->reload();
	filterComboCategory( categoryBox->currentItem() );
	#endif
}

void SelectRecipeDialog::refilter()
{
	if ( !searchBox->text().isEmpty() ) {
		ensurePopulated();
		recipeFilter->filter(searchBox->text());
	}
}

void SelectRecipeDialog::ensurePopulated()
{
	recipeListView->populateAll();
}

void SelectRecipeDialog::haveSelectedItems()
{
	if ( recipeListView->selectedItems().count() > 0 )
		emit recipeSelected( true );
	else
		emit recipeSelected( false );
}

void SelectRecipeDialog::getCurrentRecipe( Recipe *recipe )
{
	TQPtrList<TQListViewItem> items = recipeListView->selectedItems();
	if ( items.count() == 1 && items.at(0)->rtti() == 1000 ) {
		RecipeListItem * recipe_it = ( RecipeListItem* )items.at(0);
		database->loadRecipe( recipe, RecipeDB::All, recipe_it->recipeID() );
	}
}

void SelectRecipeDialog::filterComboCategory( int row )
{
	recipeListView->populateAll(); //TODO: this would be faster if we didn't need to load everything first

	kdDebug() << "I got row " << row << "\n";

	//First get the category ID corresponding to this combo row
	int categoryID = categoryBox->id( row );

	//Now filter
	recipeFilter->filterCategory( categoryID ); // if categoryID==-1 doesn't filter
	recipeFilter->filter( searchBox->text() );

	if ( categoryID != -1 ) {
	        TQListViewItemIterator it( recipeListView );
		while ( it.current() ) {
			TQListViewItem *item = it.current();
			if ( item->isVisible() ) {
				item->setOpen( true ); 	//will only open if already populated 
							//(could be the selected category's parent
				if ( !item->firstChild() ) {
					recipeListView->open( item ); //populates and opens the selected category
					break;
				}
			}
			++it;
		}
		
	}
}

RecipeActionsHandler* SelectRecipeDialog::getActionsHandler() const
{
	if ( tabWidget->currentPage() == basicSearchTab )
		return actionHandler;
	else
		return advancedSearch->actionHandler;
}

#include "selectrecipedialog.moc"
