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

#include <tdelocale.h>
#include <tdeconfig.h>
#include <kcursor.h>
#include <kdialog.h>
#include <tdeglobal.h>
#include <tdeapplication.h>

#include "backends/recipedb.h"
#include "refineshoppinglistdialog.h"
#include "datablocks/recipelist.h"
#include "widgets/recipelistview.h"
#include "recipefilter.h"
#include "recipeactionshandler.h"

/** A simple listview to accept dropping a RecipeItemDrag */
class ShoppingListView : public TDEListView
{
public:
	ShoppingListView( TQWidget *parent ) : TDEListView( parent )
	{}

protected:
	bool acceptDrag( TQDropEvent *event ) const
	{
		return RecipeItemDrag::canDecode( event );
	}

	TQDragObject *dragObject()
	{
		RecipeListItem * item = dynamic_cast<RecipeListItem*>( selectedItem() );
		if ( item != 0 ) {

			RecipeItemDrag * obj = new RecipeItemDrag( item, this, "Recipe drag item" );
			/*const TQPixmap *pm = item->pixmap(0);
			if( pm )
				obj->setPixmap( *pm );*/ 
			return obj;
		}
		return 0;
	}
};


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

	// Design dialog
	layout = new TQGridLayout( this, 2, 2, KDialog::marginHint(), KDialog::spacingHint() );

	recipeListView = new KreListView ( this, i18n( "Full recipe list" ), true, 1 );
	layout->addWidget( recipeListView, 0, 0 );
	listview = new RecipeListView( recipeListView, database );
	listview->setSizePolicy( TQSizePolicy::Ignored, TQSizePolicy::MinimumExpanding );
	listview->setDragEnabled( true );
	listview->setAcceptDrops( true );
	listview->setDropVisualizer( false );
	connect( recipeListView, SIGNAL( textChanged(const TQString&) ), SLOT( ensurePopulated() ) );
	connect( listview, SIGNAL( dropped( TDEListView*, TQDropEvent*, TQListViewItem* ) ),
	         this, SLOT( slotDropped( TDEListView*, TQDropEvent*, TQListViewItem* ) ) );
	recipeListView->setListView( listview );
	recipeListView->setCustomFilter( new RecipeFilter( recipeListView->listView() ), SLOT( filter( const TQString & ) ) );
	recipeListView->setSizePolicy( TQSizePolicy::Minimum, TQSizePolicy::MinimumExpanding );

	TQBoxLayout* vboxl = new TQVBoxLayout( KDialog::spacingHint() );
	TDEIconLoader il;
	addRecipeButton = new TQPushButton( this );
	addRecipeButton->setIconSet( il.loadIconSet( "forward", TDEIcon::Small ) );
	addRecipeButton->setFixedSize( TQSize( 32, 32 ) );
	addRecipeButton->setFlat( true );
	vboxl->addWidget( addRecipeButton );

	removeRecipeButton = new TQPushButton( this );
	removeRecipeButton->setIconSet( il.loadIconSet( "back", TDEIcon::Small ) );
	removeRecipeButton->setFixedSize( TQSize( 32, 32 ) );
	removeRecipeButton->setFlat( true );
	vboxl->addWidget( removeRecipeButton );
	vboxl->addStretch();

	layout->addItem( vboxl, 0, 1 );

	shopRecipeListView = new KreListView ( this, i18n("Shopping List") );
	ShoppingListView *slistview = new ShoppingListView( shopRecipeListView );
	slistview->setSizePolicy( TQSizePolicy::Ignored, TQSizePolicy::MinimumExpanding );
	slistview->setDragEnabled( true );
	slistview->setAcceptDrops( true );
	slistview->setDropVisualizer( false );
	connect( slistview, SIGNAL( dropped( TDEListView*, TQDropEvent*, TQListViewItem* ) ),
	         this, SLOT( slotDropped( TDEListView*, TQDropEvent*, TQListViewItem* ) ) );
	shopRecipeListView->setListView( slistview );
	layout->addWidget( shopRecipeListView, 0, 2 );

	shopRecipeListView->listView() ->addColumn( i18n( "Recipe Title" ) );

	TDEConfig *config = TDEGlobal::config();
	config->setGroup( "Advanced" );
	bool show_id = config->readBoolEntry( "ShowID", false );
	shopRecipeListView->listView() ->addColumn( i18n( "Id" ), show_id ? -1 : 0 );

	shopRecipeListView->listView() ->setSorting( -1 );
	shopRecipeListView->setSizePolicy( TQSizePolicy::Minimum, TQSizePolicy::MinimumExpanding );
	shopRecipeListView->listView() ->setAllColumnsShowFocus( true );

	buttonBar = new TQHBox( this, "buttonBar" );
	layout->addMultiCellWidget( buttonBar, 1, 1, 0, 2 );

	layout->setColStretch( 0, 1 );
	layout->setColStretch( 1, 0 );
	layout->setColStretch( 2, 1 );

	okButton = new TQPushButton( buttonBar, "okButton" );
	okButton->setText( i18n( "&OK" ) );
	TQPixmap pm = il.loadIcon( "ok", TDEIcon::NoGroup, 16 );
	okButton->setIconSet( pm );

	//buttonBar->layout()->addItem( new TQSpacerItem( 10,10, TQSizePolicy::MinimumExpanding, TQSizePolicy::Fixed ) );

	clearButton = new TQPushButton( buttonBar, "clearButton" );
	clearButton->setText( i18n( "Clear" ) );
	pm = il.loadIcon( "edit-clear", TDEIcon::NoGroup, 16 );
	clearButton->setIconSet( pm );

	//Takes care of all recipe actions and provides a popup menu to 'recipeListView'
	actionHandler = new RecipeActionsHandler( recipeListView->listView(), database, RecipeActionsHandler::ExpandAll | RecipeActionsHandler::CollapseAll );

	// Connect signals & slots
	connect( addRecipeButton, SIGNAL( clicked() ), this, SLOT( addRecipe() ) );
	connect( removeRecipeButton, SIGNAL( clicked() ), this, SLOT( removeRecipe() ) );
	connect( okButton, SIGNAL( clicked() ), this, SLOT( showShoppingList() ) );
	connect( clearButton, SIGNAL( clicked() ), this, SLOT( clear() ) );
}

ShoppingListDialog::~ShoppingListDialog()
{}

void ShoppingListDialog::ensurePopulated()
{
	listview->populateAll();
}

void ShoppingListDialog::createShopping( const RecipeList &rlist )
{
	clear();
	RecipeList::const_iterator it;
	for ( it = rlist.begin(); it != rlist.end(); ++it ) {
		new RecipeListItem( shopRecipeListView->listView(), shopRecipeListView->listView() ->lastItem(), *it );
	}
}

void ShoppingListDialog::reloadRecipeList( ReloadFlags flag )
{
	( ( RecipeListView* ) recipeListView->listView() ) ->reload( flag );
}

void ShoppingListDialog::reload( ReloadFlags flag )
{
	reloadRecipeList ( flag ); // Missing: check if there's non-existing recipes in the list now, and if so, delete.
}

void ShoppingListDialog::addRecipe( void )
{
	TQPtrList<TQListViewItem> items = recipeListView->listView()->selectedItems();

	TQPtrListIterator<TQListViewItem> it(items);
	TQListViewItem *item;
	while ( (item = it.current()) != 0 ) {
		addRecipe( item );
		++it;
	}
}

void ShoppingListDialog::addRecipe( TQListViewItem *item )
{
	if ( item ) {
		if ( item->rtti() == 1000 ) {
			RecipeListItem * recipe_it = ( RecipeListItem* ) item;

			Recipe r;
			r.title = recipe_it->title();
			r.recipeID = recipe_it->recipeID();
			( void ) new RecipeListItem( shopRecipeListView->listView(), r );
		}
	}
}

void ShoppingListDialog::removeRecipe( void )
{
	TQListViewItem * it;
	it = shopRecipeListView->listView() ->selectedItem();
	if ( it )
		delete it;
}

void ShoppingListDialog::showShoppingList( void )
{
	// Store the recipe list in ElementList object first
	ElementList recipeList;
	RecipeListItem *it;
	for ( it = ( RecipeListItem* ) shopRecipeListView->listView() ->firstChild();it;it = ( RecipeListItem* ) it->nextSibling() ) {
		Element newEl;
		newEl.id = it->recipeID();
		newEl.name = it->title(); // Storing the title is not necessary, but do it just in case it's used later on
		recipeList.append( newEl );
	}

	RefineShoppingListDialog refineDialog( this, database, recipeList );
	refineDialog.exec();
}

void ShoppingListDialog::addRecipeToShoppingList( int recipeID )
{
	Recipe r;
	r.title = database->recipeTitle( recipeID );
	r.recipeID = recipeID;

	new RecipeListItem( shopRecipeListView->listView(), r );
}

void ShoppingListDialog::clear()
{
	shopRecipeListView->listView() ->clear();
}

void ShoppingListDialog::slotDropped( TDEListView *list, TQDropEvent *e, TQListViewItem * /*after*/ )
{
	Recipe r;
	RecipeListItem *item = new RecipeListItem( recipeListView->listView(), r ); // needs parent, use this temporarily
	if ( !RecipeItemDrag::decode( e, *item ) ) {
		delete item;
		return ;
	}

	if ( list == shopRecipeListView->listView() ) {
		addRecipe( item );
	}
	//find and delete the item if we just dropped onto the recipe list from the shopping list
	else if ( list == recipeListView->listView() && e->source() == shopRecipeListView->listView() ) {
		TQListViewItemIterator list_it = TQListViewItemIterator( shopRecipeListView->listView() );
		while ( list_it.current() ) {
			if ( ( ( RecipeListItem* ) list_it.current() ) ->recipeID() == item->recipeID() ) {
				delete list_it.current();
				break;
			}
			list_it++;
		}
	}

	delete item;
	item = 0; // not needed anymore
}

#include "shoppinglistdialog.moc"
