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

#include <tdemessagebox.h>
#include <tdeconfig.h>
#include <tdelocale.h>
#include <tdeglobal.h>
#include <kiconloader.h>
#include <tdepopupmenu.h>

#include "backends/recipedb.h"
#include "dialogs/createelementdialog.h"
#include "dialogs/dependanciesdialog.h"

PrepMethodListView::PrepMethodListView( TQWidget *parent, RecipeDB *db ) : DBListViewBase( parent,db,db->prepMethodCount())
{
	setAllColumnsShowFocus( true );
	setDefaultRenameAction( TQListView::Reject );
}

void PrepMethodListView::init()
{
	connect( database, SIGNAL( prepMethodCreated( const Element & ) ), SLOT( checkCreatePrepMethod( const Element & ) ) );
	connect( database, SIGNAL( prepMethodRemoved( int ) ), SLOT( removePrepMethod( int ) ) );
}

void PrepMethodListView::load( int limit, int offset )
{
	ElementList prepMethodList;
	database->loadPrepMethods( &prepMethodList, limit, offset );

	setTotalItems(prepMethodList.count());

	for ( ElementList::const_iterator ing_it = prepMethodList.begin(); ing_it != prepMethodList.end(); ++ing_it )
		createPrepMethod( *ing_it );
}

void PrepMethodListView::checkCreatePrepMethod( const Element &el )
{
	if ( handleElement(el.name) ) { //only create this prep method if the base class okays it
		createPrepMethod(el);
	}
}


StdPrepMethodListView::StdPrepMethodListView( TQWidget *parent, RecipeDB *db, bool editable ) : PrepMethodListView( parent, db )
{
	addColumn( i18n( "Preparation Method" ) );

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

	if ( editable ) {
		setRenameable( 0, true );

		TDEIconLoader *il = new TDEIconLoader;

		kpop = new TDEPopupMenu( this );
		kpop->insertItem( il->loadIcon( "document-new", TDEIcon::NoGroup, 16 ), i18n( "&Create" ), this, SLOT( createNew() ), CTRL + Key_C );
		kpop->insertItem( il->loadIcon( "edit-delete", TDEIcon::NoGroup, 16 ), i18n( "&Delete" ), this, SLOT( remove
			                  () ), Key_Delete );
		kpop->insertItem( il->loadIcon( "edit", TDEIcon::NoGroup, 16 ), i18n( "&Rename" ), this, SLOT( rename() ), CTRL + Key_R );
		kpop->polish();

		delete il;

		connect( this, SIGNAL( contextMenu( TDEListView *, TQListViewItem *, const TQPoint & ) ), SLOT( showPopup( TDEListView *, TQListViewItem *, const TQPoint & ) ) );
		connect( this, SIGNAL( doubleClicked( TQListViewItem* ) ), this, SLOT( modPrepMethod( TQListViewItem* ) ) );
		connect( this, SIGNAL( itemRenamed( TQListViewItem* ) ), this, SLOT( savePrepMethod( TQListViewItem* ) ) );
	}
}

void StdPrepMethodListView::showPopup( TDEListView * /*l*/, TQListViewItem *i, const TQPoint &p )
{
	if ( i )
		kpop->exec( p );
}

void StdPrepMethodListView::createNew()
{
	CreateElementDialog * elementDialog = new CreateElementDialog( this, i18n( "New Preparation Method" ) );

	if ( elementDialog->exec() == TQDialog::Accepted ) {
		TQString result = elementDialog->newElementName();

		//check bounds first
		if ( checkBounds( result ) )
			database->createNewPrepMethod( result ); // Create the new prepMethod in the database
	}
}

void StdPrepMethodListView::remove
	()
{
	TQListViewItem * item = currentItem();

	if ( item ) {
		ElementList dependingRecipes;
		int prepMethodID = item->text( 1 ).toInt();
		database->findPrepMethodDependancies( prepMethodID, &dependingRecipes );
		if ( dependingRecipes.isEmpty() )
			database->removePrepMethod( prepMethodID );
		else // Need Warning!
		{
			ListInfo info;
			info.list = dependingRecipes;
			info.name = i18n("Recipes");
			DependanciesDialog warnDialog( this, info );
			warnDialog.setCustomWarning( i18n("You are about to permanantly delete recipes from your database.") );
			if ( warnDialog.exec() == TQDialog::Accepted )
				database->removePrepMethod( prepMethodID );
		}
	}
}

void StdPrepMethodListView::rename()
{
	TQListViewItem * item = currentItem();

	if ( item )
		PrepMethodListView::rename( item, 0 );
}

void StdPrepMethodListView::createPrepMethod( const Element &ing )
{
	createElement(new TQListViewItem( this, ing.name, TQString::number( ing.id ) ));
}

void StdPrepMethodListView::removePrepMethod( int id )
{
	TQListViewItem * item = findItem( TQString::number( id ), 1 );
	removeElement(item);
}

void StdPrepMethodListView::modPrepMethod( TQListViewItem* i )
{
	if ( i )
		PrepMethodListView::rename( i, 0 );
}

void StdPrepMethodListView::savePrepMethod( TQListViewItem* i )
{
	if ( !checkBounds( i->text( 0 ) ) ) {
		reload(ForceReload); //reset the changed text
		return ;
	}

	int existing_id = database->findExistingPrepByName( i->text( 0 ) );
	int prep_id = i->text( 1 ).toInt();
	if ( existing_id != -1 && existing_id != prep_id )  //category already exists with this label... merge the two
	{
		switch ( KMessageBox::warningContinueCancel( this, i18n( "This preparation method already exists.  Continuing will merge these two into one.  Are you sure?" ) ) )
		{
		case KMessageBox::Continue: {
				database->mergePrepMethods( existing_id, prep_id );
				break;
			}
		default:
			reload(ForceReload);
			break;
		}
	}
	else {
		database->modPrepMethod( ( i->text( 1 ) ).toInt(), i->text( 0 ) );
	}
}

bool StdPrepMethodListView::checkBounds( const TQString &name )
{
	if ( name.length() > uint(database->maxPrepMethodNameLength()) ) {
		KMessageBox::error( this, TQString( i18n( "Preparation method cannot be longer than %1 characters." ) ).arg( database->maxPrepMethodNameLength() ) );
		return false;
	}

	return true;
}

#include "prepmethodlistview.moc"
