/***************************************************************************
*   Copyright (C) 2004 by 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 "refineshoppinglistdialog.h"

#include <tqvariant.h>
#include <tqpushbutton.h>
#include <tqlabel.h>
#include <tqheader.h>
#include <tqlayout.h>
#include <tqtooltip.h>
#include <tqwhatsthis.h>

#include <tdelocale.h>
#include <kiconloader.h>
#include <tdeapplication.h>
#include <kcursor.h>
#include <tdeconfig.h>

#include "backends/recipedb.h"
#include "widgets/krelistview.h"
#include "widgets/ingredientlistview.h"
#include "shoppinglistviewdialog.h"
#include "shoppingcalculator.h"
#include "datablocks/mixednumber.h"

RefineShoppingListDialog::RefineShoppingListDialog( TQWidget* parent, RecipeDB *db, const ElementList &recipeList )
		: KDialogBase( parent, "refinedialog", true, TQString::null,
		    KDialogBase::Ok, KDialogBase::Ok ),
		database( db )
{
	setButtonText( KDialogBase::Ok, i18n( "&Done" ) );

	TQVBox *page = makeVBoxMainWidget();

	helpLabel = new TQLabel( page, "helpLabel" );
	helpLabel->setTextFormat( TQLabel::RichText );

	TQWidget *layout2Widget = new TQWidget(page);

	TQHBoxLayout *layout2 = new TQHBoxLayout( layout2Widget, 0, 6, "layout2" );

	allIngListView = new KreListView( layout2Widget, TQString::null, true, 0 );
	StdIngredientListView *list_view = new StdIngredientListView(allIngListView,database);
	list_view->reload();
 	allIngListView->setListView(list_view);
	layout2->addWidget( allIngListView );

	layout1 = new TQVBoxLayout( 0, 0, 6, "layout1" );

	TDEIconLoader il;

	addButton = new TQPushButton( layout2Widget, "addButton" );
	addButton->setIconSet( il.loadIconSet( "forward", TDEIcon::Small ) );
	addButton->setFixedSize( TQSize( 32, 32 ) );
	layout1->addWidget( addButton );

	removeButton = new TQPushButton( layout2Widget, "removeButton" );
	removeButton->setIconSet( il.loadIconSet( "back", TDEIcon::Small ) );
	removeButton->setFixedSize( TQSize( 32, 32 ) );
	layout1->addWidget( removeButton );
	spacer1 = new TQSpacerItem( 51, 191, TQSizePolicy::Minimum, TQSizePolicy::Expanding );
	layout1->addItem( spacer1 );
	layout2->addLayout( layout1 );

	ingListView = new KreListView( layout2Widget, TQString::null, true );
	ingListView->listView() ->addColumn( i18n( "Ingredients in Shopping List" ) );
	ingListView->listView() ->addColumn( i18n( "Amount" ) );
	ingListView->listView() ->addColumn( i18n( "Unit" ) );
	ingListView->listView() ->setItemsRenameable( true );
	ingListView->listView() ->setRenameable( 0, false );
	ingListView->listView() ->setRenameable( 1, true );
	ingListView->listView() ->setRenameable( 2, true );
	layout2->addWidget( ingListView );

	languageChange();

	clearWState( WState_Polished );

	connect( addButton, TQ_SIGNAL( clicked() ), this, TQ_SLOT( addIngredient() ) );
	connect( removeButton, TQ_SIGNAL( clicked() ), this, TQ_SLOT( removeIngredient() ) );
	connect( ingListView->listView(), TQ_SIGNAL( itemRenamed( TQListViewItem*, const TQString &, int ) ), TQ_SLOT( itemRenamed( TQListViewItem*, const TQString &, int ) ) );

	TDEApplication::setOverrideCursor( KCursor::waitCursor() );
	calculateShopping( recipeList, &ingredientList, database );
	TDEApplication::restoreOverrideCursor();

	loadData();
}

RefineShoppingListDialog::~RefineShoppingListDialog()
{}

void RefineShoppingListDialog::languageChange()
{
	helpLabel->setText( i18n( "On the right are the ingredients needed for the recipes you selected.  You may now add additional ingredients, remove ingredients you do not need, or modify the amounts of existing ingredients." ) );
	allIngListView->listView() ->header() ->setLabel( 0, i18n( "Ingredients" ) );
	ingListView->listView() ->header() ->setLabel( 0, i18n( "Ingredients in Shopping List" ) );
	ingListView->listView() ->header() ->setLabel( 1, i18n( "Amount" ) );
	ingListView->listView() ->header() ->setLabel( 2, i18n( "Unit" ) );
}

void RefineShoppingListDialog::accept()
{
	hide();

	ShoppingListViewDialog view( this, ingredientList );
	view.exec();

	TQDialog::accept();
}

void RefineShoppingListDialog::loadData()
{
	for ( IngredientList::iterator it = ingredientList.begin(); it != ingredientList.end(); ++it ) {
		//from here on, the shopping list will work with the upper value of the range (if exists)
		(*it).amount = (*it).amount+(*it).amount_offset;
		(*it).amount_offset = 0;

		TQString amount_str;
		if ( ( *it ).amount > 0 ) {
			TDEConfig * config = tdeApp->config();
			config->setGroup( "Formatting" );
	
			if ( config->readBoolEntry( "Fraction" ) )
				amount_str = MixedNumber( ( *it ).amount ).toString();
			else
				amount_str = beautify( TDEGlobal::locale() ->formatNumber( ( *it ).amount, 5 ) );
		}

		TQListViewItem *new_item = new TQListViewItem( ingListView->listView(), ( *it ).name, amount_str, ( *it ).amount > 1 ? ( *it ).units.plural : ( *it ).units.name );
		item_ing_map.insert( new_item, it );
	}
}

void RefineShoppingListDialog::addIngredient()
{
	TQListViewItem * item = allIngListView->listView() ->selectedItem();
	if ( item ) {
		TQListViewItem * new_item = new TQListViewItem( ingListView->listView(), item->text( 0 ) );
		ingListView->listView() ->setSelected( new_item, true );
		ingListView->listView() ->ensureItemVisible( new_item );
		allIngListView->listView() ->setSelected( item, false );

		item_ing_map.insert( new_item, ingredientList.append( Ingredient( item->text( 0 ), 0, Unit() ) ) );
	}
}

void RefineShoppingListDialog::removeIngredient()
{
	TQListViewItem * item = ingListView->listView() ->selectedItem();
	if ( item ) {
		for ( IngredientList::iterator it = ingredientList.begin(); it != ingredientList.end(); ++it ) {
			if ( *item_ing_map.find( item ) == it ) {
				ingredientList.remove( it );
				item_ing_map.remove( item );
				break;
			}
		}
		delete item;
	}
}

void RefineShoppingListDialog::itemRenamed( TQListViewItem* item, const TQString &new_text, int col )
{
	if ( col == 1 ) {
		IngredientList::iterator found_it = *item_ing_map.find( item );

		bool ok;
		MixedNumber amount = MixedNumber::fromString( new_text, &ok );
		if ( ok ) {
			( *found_it ).amount = amount.toDouble();
		}
		else { //revert back to the valid amount string
			TQString amount_str;
			if ( ( *found_it ).amount > 0 ) {
				TDEConfig * config = tdeApp->config();
				config->setGroup( "Formatting" );
		
				if ( config->readBoolEntry( "Fraction" ) )
					amount_str = MixedNumber( ( *found_it ).amount ).toString();
				else
					amount_str = beautify( TDEGlobal::locale() ->formatNumber( ( *found_it ).amount, 5 ) );
			}

			item->setText( 1, amount_str );
		}
	}
	else if ( col == 2 ) {
		IngredientList::iterator found_it = *item_ing_map.find( item );

		if ( ( *found_it ).amount > 1 )
			( *found_it ).units.plural = new_text;
		else
			( *found_it ).units.name = new_text;
	}
}

#include "refineshoppinglistdialog.moc"
