/***************************************************************************
*   Copyright (C) 2004-2009 by Thomas Fischer                             *
*   fischer@unix-ag.uni-kl.de                                             *
*                                                                         *
*   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.                                   *
*                                                                         *
*   This program is distributed in the hope that it will be useful,       *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU General Public License for more details.                          *
*                                                                         *
*   You should have received a copy of the GNU General Public License     *
*   along with this program; if not, write to the                         *
*   Free Software Foundation, Inc.,                                       *
*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
***************************************************************************/
#include <ntqlayout.h>
#include <ntqcombobox.h>
#include <ntqheader.h>
#include <ntqapplication.h>
#include <ntqtooltip.h>
#include <ntqstring.h>
#include <ntqtoolbutton.h>

#include <kdebug.h>
#include <tdepopupmenu.h>
#include <tdelistview.h>
#include <kdialog.h>
#include <tdelocale.h>
#include <kiconloader.h>

#include <settings.h>
#include <entry.h>
#include "sidebar.h"

namespace KBibTeX
{

    const BibTeX::EntryField::FieldType SideBar::importantFields[ 6 ] =
    {
        BibTeX::EntryField::ftAuthor, BibTeX::EntryField::ftBookTitle, BibTeX::EntryField::ftJournal, BibTeX::EntryField::ftTitle, BibTeX::EntryField::ftYear, BibTeX::EntryField::ftKeywords
    };

    SideBar::SideBar( bool isReadOnly, TQWidget *parent, const char *name )
            : TQWidget( parent, name ), m_bibtexFile( NULL ), m_isReadOnly( isReadOnly ), m_popupMenu( NULL )
    {
        setupGUI();
    }

    SideBar::~SideBar()
    {
        // nothing
    }

    void SideBar::restoreState()
    {
        Settings * settings = Settings::self();
        if ( settings->editing_UseSpecialFont )
            m_listAvailableItems->setFont( settings->editing_SpecialFont );
        else
            m_listAvailableItems->setFont( TDEGlobalSettings::generalFont() );
        m_listAvailableItems->header() ->setFont( TDEGlobalSettings::generalFont() );
    }

    void SideBar::refreshLists( BibTeX::File *bibtexFile )
    {
        if ( bibtexFile != NULL )
            m_bibtexFile = bibtexFile;

        TQApplication::setOverrideCursor( TQt::waitCursor );
        setEnabled( FALSE );

        BibTeX::EntryField::FieldType fieldType = m_buttonToggleShowAll->isOn() ? ( BibTeX::EntryField::FieldType )( m_listTypeList->currentItem() + ( int ) BibTeX::EntryField::ftAbstract ) : importantFields[ m_listTypeList->currentItem()];

        m_listAvailableItems->clear();
        if ( m_bibtexFile != NULL )
        {
            TQMap<TQString, int> allValues = m_bibtexFile->getAllValuesAsStringListWithCount( fieldType );
            for ( TQMap<TQString, int>::ConstIterator it = allValues.constBegin(); it != allValues.constEnd();++it )
            {
                TQString text = it.key();
                if ( !text.startsWith( "other" ) )
                    new SideBarListViewItem( m_listAvailableItems, TQString::number( it.data() ), text );
            }
        }

        setEnabled( TRUE );
        TQApplication::restoreOverrideCursor();
    }

    void SideBar::resizeEvent( TQResizeEvent *event )
    {
        TQSize widgetSize = size();
        setEnabled( widgetSize.width() > 3 && widgetSize.height() > 3 );
        TQWidget::resizeEvent( event );
    }

    void SideBar::setupGUI()
    {
        TQGridLayout * layout = new TQGridLayout( this, 2, 3, 0, KDialog::spacingHint() );
        layout->setColStretch( 0, 0 );
        layout->setColStretch( 1, 10 );
        layout->setColStretch( 2, 0 );

        m_buttonToggleShowAll = new TQToolButton( this );
        layout->addWidget( m_buttonToggleShowAll, 0, 0 );
        TQIconSet showAllPixmap = TDEGlobal::iconLoader() ->loadIconSet( "taskbar", TDEIcon::Small );
        m_buttonToggleShowAll->setIconSet( showAllPixmap );
        m_buttonToggleShowAll->setToggleButton( TRUE );
        TQToolTip::add( m_buttonToggleShowAll, i18n( "Toggle between showing all fields or only important fields" ) );

        m_listTypeList = new TQComboBox( FALSE, this );
        layout->addWidget( m_listTypeList, 0, 1 );
        TQToolTip::add( m_listTypeList, i18n( "Filter this sidebar for a given field" ) );

        m_buttonToggleMultiSelect = new TQToolButton( this );
        layout->addWidget( m_buttonToggleMultiSelect, 0, 2 );
        showAllPixmap = TDEGlobal::iconLoader() ->loadIconSet( "planner", TDEIcon::Small );
        m_buttonToggleMultiSelect->setIconSet( showAllPixmap );
        m_buttonToggleMultiSelect->setToggleButton( TRUE );
        TQToolTip::add( m_buttonToggleMultiSelect, i18n( "Toggle between selecting only one item or multiple items (AND-connected in search)" ) );

        m_listAvailableItems = new TDEListView( this );
        m_listAvailableItems->addColumn( i18n( "#" ) );
        m_listAvailableItems->addColumn( i18n( "Items" ) );
        m_listAvailableItems->setAllColumnsShowFocus( TRUE );
        m_listAvailableItems->setFullWidth( true );
        m_listAvailableItems->setSorting( 1 );
        layout->addMultiCellWidget( m_listAvailableItems, 1, 1, 0, 2 );

        m_popupMenu = new TDEPopupMenu( m_listAvailableItems );
        m_popupMenu->insertItem( i18n( "Rename all occurrences" ), this, SLOT( startRenaming() ) );

        connect( m_listAvailableItems, SIGNAL( selectionChanged() ), this, SLOT( prepareSearch() ) );
        connect( m_listTypeList, SIGNAL( activated( int ) ), this, SLOT( refreshLists() ) );
        connect( m_buttonToggleShowAll, SIGNAL( toggled( bool ) ), this, SLOT( toggleShowAll( bool ) ) );
        connect( m_buttonToggleMultiSelect, SIGNAL( toggled( bool ) ), this, SLOT( toggleMultiSelect( bool ) ) );
        connect( m_listAvailableItems, SIGNAL( contextMenuRequested( TQListViewItem*, const TQPoint&, int ) ), this, SLOT( showContextMenu( TQListViewItem*, const TQPoint& ) ) );
        connect( m_listAvailableItems, SIGNAL( itemRenamed( TQListViewItem*, int, const TQString& ) ), this, SLOT( endRenaming( TQListViewItem*, int, const TQString& ) ) );

        toggleShowAll( FALSE );
    }

    void SideBar::setReadOnly( bool isReadOnly )
    {
        m_isReadOnly = isReadOnly;
    }


    void SideBar::prepareSearch()
    {
        BibTeX::EntryField::FieldType fieldType = m_buttonToggleShowAll->isOn() ? ( BibTeX::EntryField::FieldType )( m_listTypeList->currentItem() + ( int ) BibTeX::EntryField::ftAbstract ) : importantFields[ m_listTypeList->currentItem()];

        TQString text = "";
        int countSelected = 0;
        for ( TQListViewItemIterator it( m_listAvailableItems, TQListViewItemIterator::Selected ); it.current(); ++it, ++countSelected )
        {
            if ( !text.isEmpty() ) text += " ";
            text += it.current()->text( 1 );
        }

        emit selected( text, countSelected <= 1 ? BibTeX::Element::ftExact : BibTeX::Element::ftEveryWord, fieldType );
    }

    void SideBar::toggleShowAll( bool showAll )
    {
        m_listTypeList->clear();

        if ( showAll )
        {
            for ( int i = ( int ) BibTeX::EntryField::ftAbstract; i <= ( int ) BibTeX::EntryField::ftYear; i++ )
            {
                BibTeX::EntryField::FieldType fieldType = ( BibTeX::EntryField::FieldType ) i;
                m_listTypeList->insertItem( Settings::fieldTypeToI18NString( fieldType ) );
            }
            m_listTypeList->setCurrentItem(( int ) BibTeX::EntryField::ftAuthor );
        }
        else
        {
            for ( int i = 0; i < 6;i++ )
                m_listTypeList->insertItem( Settings::fieldTypeToI18NString( importantFields[ i ] ) );
            m_listTypeList->setCurrentItem( 0 );
        }

        refreshLists();
    }

    void SideBar::toggleMultiSelect( bool multiSelect )
    {
        m_listAvailableItems->setSelectionMode( multiSelect ? TQListView::Extended : TQListView::Single );
        m_listAvailableItems->clearSelection();
        prepareSearch();
    }

    void SideBar::showContextMenu( TQListViewItem * item, const TQPoint & pos )
    {
        if ( item != NULL && !m_isReadOnly && m_popupMenu != NULL )
            m_popupMenu->exec( pos );
    }

    void SideBar::startRenaming()
    {
        TQListViewItem * item = m_listAvailableItems->selectedItem();
        if ( item == NULL )
            item = m_listAvailableItems->currentItem();

        if ( item != NULL )
        {
            m_oldText = item->text( 1 );
            item->setRenameEnabled( 1, TRUE );
            item->startRename( 1 );
        }
    }

    void SideBar::endRenaming( TQListViewItem * item, int , const TQString & text )
    {
        item->setRenameEnabled( 1, FALSE );
        BibTeX::EntryField::FieldType fieldType = m_buttonToggleShowAll->isOn() ? ( BibTeX::EntryField::FieldType )( m_listTypeList->currentItem() + ( int ) BibTeX::EntryField::ftAbstract ) : importantFields[ m_listTypeList->currentItem()];
        m_bibtexFile->replaceValue( m_oldText, text, fieldType );

        m_listAvailableItems->clearSelection();
        m_listAvailableItems->setSelected( item, true );
        prepareSearch();

        emit valueRenamed();
    }

    SideBarListViewItem::SideBarListViewItem( TQListView *parent, TQString label1, TQString label2 ) : TQListViewItem( parent, label1, label2 )
    {
// nothing
    }

    int SideBarListViewItem::compare( TQListViewItem* item, int column, bool ascending ) const
    {
        if ( column == 0 )
        {
            bool ok = FALSE;
            int ownValue = text( 0 ).toInt( &ok );
            if ( ok )
            {
                int otherValue = item->text( 0 ).toInt( &ok );
                if ( ok )
                {
                    return ownValue < otherValue ? -1 : ( ownValue > otherValue ? 1 : 0 );
                }
            }
        }

        return TQListViewItem::compare( item, column, ascending );
    }
}
#include "sidebar.moc"