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

#include <tqmessagebox.h>
#include <tqvbox.h>

#include <tdeconfig.h>
#include <kdialog.h>
#include <tdelocale.h>
#include <tdemessagebox.h>
#include <tdeglobal.h>

#include "backends/recipedb.h"

SelectAuthorsDialog::SelectAuthorsDialog( TQWidget *parent, const ElementList &currentAuthors, RecipeDB *db )
		: KDialogBase( parent, "SelectAuthorsDialog", true, i18n("Authors"),
		    KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok ),
		database(db)
{
	TQVBox *page = makeVBoxMainWidget();

	//Design UI

	// Combo to Pick authors
	TQHBox *topBox = new TQHBox(page);
	topBox->setSpacing(6);

	authorsCombo = new KComboBox( true, topBox );
	authorsCombo->setSizePolicy( TQSizePolicy( TQSizePolicy::MinimumExpanding, TQSizePolicy::MinimumExpanding ) );
	authorsCombo->completionObject() ->setCompletionMode( TDEGlobalSettings::CompletionPopupAuto );
	authorsCombo->lineEdit() ->disconnect( authorsCombo ); //so hitting enter doesn't enter the item into the box
	
	// Add/Remove buttons

	il = new TDEIconLoader;
	addAuthorButton = new TQPushButton( topBox );
	TQPixmap pm = il->loadIcon( "go-down", TDEIcon::NoGroup, 16 );
	addAuthorButton->setIconSet( pm );

	removeAuthorButton = new TQPushButton( topBox );
	pm = il->loadIcon( "go-up", TDEIcon::NoGroup, 16 );
	removeAuthorButton->setIconSet( pm );

	// Author List

	authorListView = new TDEListView( page );
	authorListView->setSizePolicy( TQSizePolicy( TQSizePolicy::MinimumExpanding, TQSizePolicy::MinimumExpanding ) );

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

	// Load the list
	loadAuthors( currentAuthors );

	adjustSize();
	resize(450, height());

	// Connect signals & Slots
	connect ( addAuthorButton, TQ_SIGNAL( clicked() ), this, TQ_SLOT( addAuthor() ) );
	connect ( removeAuthorButton, TQ_SIGNAL( clicked() ), this, TQ_SLOT( removeAuthor() ) );

	authorsCombo->setEditText(TQString::null);
	authorsCombo->lineEdit()->setFocus();
}

SelectAuthorsDialog::~SelectAuthorsDialog()
{}

void SelectAuthorsDialog::getSelectedAuthors( ElementList *newAuthors )
{

	for ( TQListViewItem * it = authorListView->firstChild();it; it = it->nextSibling() ) {
		Element author;
		author.id = it->text( 0 ).toInt();
		author.name = it->text( 1 );
		newAuthors->append( author );
	}

}

void SelectAuthorsDialog::loadAuthors( const ElementList &currentAuthors )
{

	// Load the combo
	reloadAuthorsCombo();

	// Load the ListView with the authors of this recipe
	authorListView->clear();
	for ( ElementList::const_iterator author_it = currentAuthors.begin(); author_it != currentAuthors.end(); ++author_it ) {
		( void ) new TQListViewItem( authorListView, TQString::number( ( *author_it ).id ), ( *author_it ).name );
	}

}

void SelectAuthorsDialog::addAuthor( void )
{
	//check bounds first
	if ( authorsCombo->currentText().length() > uint(database->maxAuthorNameLength()) ) {
		KMessageBox::error( this, TQString( i18n( "Author name cannot be longer than %1 characters." ) ).arg( database->maxAuthorNameLength() ) );
		authorsCombo->lineEdit() ->selectAll();
		return ;
	}

	if ( authorsCombo->lineEdit()->text().isEmpty() )
		return;

	if ( authorsCombo->contains( authorsCombo->currentText() ) )
		authorsCombo->setCurrentItem( authorsCombo->currentText() );

	createNewAuthorIfNecessary();

	int currentItem = authorsCombo->currentItem();
	Element currentElement = authorList.getElement( currentItem );

	( void ) new TQListViewItem( authorListView, TQString::number( currentElement.id ), currentElement.name );

}

void SelectAuthorsDialog::removeAuthor( void )
{
	// Find the selected item first
	TQListViewItem * it;
	it = authorListView->selectedItem();

	if ( it ) {  // Check if an author is selected first
		delete it;
	}

}

void SelectAuthorsDialog::createNewAuthorIfNecessary( void )
{

	if ( !authorsCombo->contains( authorsCombo->currentText() ) &&
	        !( authorsCombo->currentText().stripWhiteSpace() ).isEmpty() )  // author is not in the list and is not empty
	{ // Create new author
		TQString newAuthorName = authorsCombo->currentText();
		database->createNewAuthor( newAuthorName );
		//List again the authors
		reloadAuthorsCombo();

		// Select the newly created author
		authorsCombo->setCurrentItem( newAuthorName );
	}
}


void SelectAuthorsDialog::reloadAuthorsCombo( void )
{

	//Load the author list
	database->loadAuthors( &authorList );

	// Load combo with all the authors
	authorsCombo->clear();
	authorsCombo->completionObject() ->clear();

	for ( ElementList::const_iterator author_it = authorList.begin(); author_it != authorList.end(); ++author_it ) {
		authorsCombo->insertItem( ( *author_it ).name );
		authorsCombo->completionObject() ->addItem( ( *author_it ).name );
	}

}


#include "selectauthorsdialog.moc"
