/***************************************************************************
*   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 <tqlistview.h>
#include <tqlayout.h>
#include <tqlabel.h>
#include <tqheader.h>
#include <tqpushbutton.h>

#include <kdialogbase.h>
#include <tdelocale.h>
#include <kiconloader.h>

#include "value.h"
#include "settings.h"
#include "valuewidget.h"

namespace KBibTeX
{

    TQDialog::DialogCode ValueWidget::execute( const TQString& title, BibTeX::EntryField::FieldType fieldType, BibTeX::Value *value, bool isReadOnly, TQWidget *parent, const char *name )
    {
        KDialogBase * dlg = new KDialogBase( parent, name, true, TQString( i18n( "Edit field '%1'" ) ).arg( title ), KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok, true );

        ValueWidget* valueWidget = new ValueWidget( fieldType, value, isReadOnly, dlg, "kbibtexvaluewidget" );
        dlg->setMainWidget( valueWidget );
        connect( dlg, TQ_SIGNAL( okClicked() ), valueWidget, TQ_SLOT( apply() ) );

        TQDialog::DialogCode result = ( TQDialog::DialogCode )dlg->exec();
        if ( isReadOnly ) result = TQDialog::Rejected;

        delete( valueWidget );
        delete( dlg );

        return result;
    }

    ValueWidget::ValueWidget( BibTeX::EntryField::FieldType fieldType, BibTeX::Value *value, bool isReadOnly, TQWidget *parent, const char *name )
            : TQWidget( parent, name ), m_fieldType( fieldType ), m_value( value ), m_newValueCounter( 0 ), m_isReadOnly( isReadOnly )
    {
        setupGUI();
        reset();
        updateGUI();
    }


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

    void ValueWidget::applyList( TQStringList& list )
    {
        if ( m_fieldType == BibTeX::EntryField::ftKeywords )
        {
            BibTeX::KeywordContainer *container = new  BibTeX::KeywordContainer();
            for ( TQStringList::Iterator it = list.begin(); it != list.end(); ++it )
                container->keywords.append( new BibTeX::Keyword( *it ) );
            m_value->items.append( container );
        }
        else if ( m_fieldType == BibTeX::EntryField::ftAuthor || m_fieldType == BibTeX::EntryField::ftEditor )
        {
            Settings * settings = Settings::self();
            BibTeX::PersonContainer *container = new  BibTeX::PersonContainer();
            for ( TQStringList::Iterator it = list.begin(); it != list.end(); ++it )
                container->persons.append( new BibTeX::Person( *it, settings->editing_FirstNameFirst ) );
            m_value->items.append( container );
        }
        else
        {
            for ( TQStringList::Iterator it = list.begin(); it != list.end(); ++it )
                m_value->items.append( new BibTeX::PlainText( *it ) );
        }

        list.clear();
    }

    void ValueWidget::apply( )
    {
        if ( m_isReadOnly ) return;

        TQStringList list;
        m_value->items.clear();
        TQListViewItem *item = m_listViewValue->firstChild();
        while ( item != NULL )
        {
            TQCheckListItem * checkItem = dynamic_cast<TQCheckListItem*>( item );
            TQString text = checkItem->text( 0 );

            if ( checkItem->state() == TQCheckListItem::On )
            {
                if ( !list.isEmpty() ) applyList( list );
                m_value->items.append( new BibTeX::MacroKey( text ) );
            }
            else
                list.append( text );
            item = item->nextSibling();
        }

        if ( !list.isEmpty() )
            applyList( list );
    }

    void ValueWidget::reset( )
    {
        m_listViewValue->clear();

        TQCheckListItem *after = NULL;
        for ( TQValueList<BibTeX::ValueItem*>::ConstIterator it = m_value->items.begin(); it != m_value->items.end(); ++it )
        {
            BibTeX::MacroKey *macroKey = dynamic_cast<BibTeX::MacroKey*>( *it );
            TQCheckListItem *item = new TQCheckListItem( m_listViewValue, after, ( *it )->text(), TQCheckListItem::CheckBox );
            after = item;
            item->setState( macroKey != NULL ? TQCheckListItem::On : TQCheckListItem::Off );
            item->setRenameEnabled( 0, !m_isReadOnly );
        }
    }

    void ValueWidget::slotAdd()
    {
        TQCheckListItem * item = new TQCheckListItem( m_listViewValue, m_listViewValue->lastItem(), TQString( i18n( "May only contain ASCII characters, in case of doubt keep English form", "NewValue%1" ) ).arg( m_newValueCounter++ ), TQCheckListItem::CheckBox );
        item->setState( TQCheckListItem::Off );
        item->setRenameEnabled( 0, !m_isReadOnly );
        m_listViewValue->setSelected( item, true );
        slotEdit();
    }

    void ValueWidget::slotEdit()
    {
        TQListViewItem * item = m_listViewValue->selectedItem();
        if ( item != NULL )
            item->startRename( 0 );
    }

    void ValueWidget::slotToggle()
    {
        TQListViewItem * item = m_listViewValue->selectedItem();
        if ( item != NULL )
        {
            TQCheckListItem * checkItem = dynamic_cast<TQCheckListItem*>( item );
            if ( checkItem != NULL )
                checkItem->setOn( !checkItem->isOn() );
        }
    }

    void ValueWidget::slotDelete()
    {
        TQListViewItem * item = m_listViewValue->selectedItem();
        if ( item != NULL )
            delete item;
        updateGUI();
    }

    void ValueWidget::slotUp()
    {
        TQListViewItem * item = m_listViewValue->selectedItem();
        if ( item != NULL && item -> itemAbove() != NULL )
        {
            item->itemAbove() ->moveItem( item );
            updateGUI();
        }
    }

    void ValueWidget::slotDown()
    {
        TQListViewItem * item = m_listViewValue->selectedItem();
        if ( item != NULL && item -> itemBelow() != NULL )
        {
            item->moveItem( item->itemBelow() );
            updateGUI();
        }
    }

    void ValueWidget::updateGUI()
    {
        bool isElementSelected = m_listViewValue->selectedItem() != NULL;
        m_pushButtonEdit->setEnabled( !m_isReadOnly && isElementSelected );
        m_pushButtonToggle->setEnabled( !m_isReadOnly && isElementSelected );
        m_pushButtonDelete->setEnabled( !m_isReadOnly && isElementSelected );
        m_pushButtonUp->setEnabled( !m_isReadOnly && isElementSelected && m_listViewValue->selectedItem() != m_listViewValue->firstChild() );
        m_pushButtonDown->setEnabled( !m_isReadOnly && isElementSelected && m_listViewValue->selectedItem() != m_listViewValue->lastItem() );
    }

    void ValueWidget::setupGUI()
    {
        TQGridLayout * layout = new TQGridLayout( this, 8, 2, 0, KDialog::spacingHint() );
        layout->setRowStretch( 7, 1 );

        TQLabel *label = new TQLabel( i18n( "Checked entries are string keys, unchecked entries are quoted text." ), this );
        layout->addWidget( label, 0, 0 );

        m_listViewValue = new TQListView( this );
        layout->addMultiCellWidget( m_listViewValue, 1, 7, 0, 0 );
        m_listViewValue->setDefaultRenameAction( m_isReadOnly ? TQListView::Reject : TQListView::Accept );
        m_listViewValue->addColumn( i18n( "Text" ) );
        m_listViewValue->setSorting( -1, true );
        m_listViewValue->setAllColumnsShowFocus( true );
        m_listViewValue->header() ->setClickEnabled( false );
        m_listViewValue->header() ->setStretchEnabled( true, 0 );
        m_listViewValue->setEnabled( !m_isReadOnly );
        connect( m_listViewValue, TQ_SIGNAL( selectionChanged() ), this, TQ_SLOT( updateGUI() ) );
        connect( m_listViewValue, TQ_SIGNAL( clicked( TQListViewItem * ) ), this, TQ_SLOT( updateGUI() ) );
        connect( m_listViewValue, TQ_SIGNAL( currentChanged( TQListViewItem * ) ), this, TQ_SLOT( updateGUI() ) );

        m_pushButtonAdd = new TQPushButton( i18n( "Add" ), this );
        layout->addWidget( m_pushButtonAdd, 1, 1 );
        m_pushButtonAdd->setIconSet( TQIconSet( SmallIcon( "add" ) ) );
        m_pushButtonAdd->setEnabled( !m_isReadOnly );
        connect( m_pushButtonAdd, TQ_SIGNAL( clicked() ), this, TQ_SLOT( slotAdd() ) );

        m_pushButtonEdit = new TQPushButton( i18n( "Edit" ), this );
        layout->addWidget( m_pushButtonEdit, 2, 1 );
        m_pushButtonEdit->setIconSet( TQIconSet( SmallIcon( "edit" ) ) );
        connect( m_pushButtonEdit, TQ_SIGNAL( clicked() ), this, TQ_SLOT( slotEdit() ) );

        m_pushButtonToggle = new TQPushButton( i18n( "Toggle" ), this );
        layout->addWidget( m_pushButtonToggle, 3, 1 );
        m_pushButtonToggle->setIconSet( TQIconSet( SmallIcon( "flag" ) ) );
        connect( m_pushButtonToggle, TQ_SIGNAL( clicked() ), this, TQ_SLOT( slotToggle() ) );

        m_pushButtonDelete = new TQPushButton( i18n( "Delete" ), this );
        layout->addWidget( m_pushButtonDelete, 4, 1 );
        m_pushButtonDelete->setIconSet( TQIconSet( SmallIcon( "edit-delete" ) ) );
        connect( m_pushButtonDelete, TQ_SIGNAL( clicked() ), this, TQ_SLOT( slotDelete() ) );

        m_pushButtonUp = new TQPushButton( i18n( "Up" ), this );
        layout->addWidget( m_pushButtonUp, 5, 1 );
        m_pushButtonUp->setIconSet( TQIconSet( SmallIcon( "go-up" ) ) );
        connect( m_pushButtonUp, TQ_SIGNAL( clicked() ), this, TQ_SLOT( slotUp() ) );

        m_pushButtonDown = new TQPushButton( i18n( "Down" ), this );
        layout->addWidget( m_pushButtonDown, 6, 1 );
        m_pushButtonDown->setIconSet( TQIconSet( SmallIcon( "go-down" ) ) );
        connect( m_pushButtonDown, TQ_SIGNAL( clicked() ), this, TQ_SLOT( slotDown() ) );
    }

}
#include "valuewidget.moc"
