/***************************************************************************
*   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 <tqstringlist.h>
#include <tqlayout.h>
#include <tqtooltip.h>
#include <tqlabel.h>
#include <tqwhatsthis.h>

#include <kdialog.h>
#include <tdeapplication.h>
#include <tdelistview.h>
#include <tdelocale.h>
#include <kiconloader.h>
#include <tdeio/netaccess.h>
#include <kpushbutton.h>
#include <klineedit.h>

#include "fieldlineedit.h"
#include "settings.h"
#include "entrywidgetother.h"

namespace KBibTeX
{

    EntryWidgetOther::EntryWidgetOther( BibTeX::File *bibtexfile, bool isReadOnly, TQWidget *parent, const char *name )
            : EntryWidgetTab( bibtexfile, isReadOnly, parent, name ), m_isModified( false )
    {
        setupGUI();
    }

    EntryWidgetOther::~EntryWidgetOther()
    {
        m_listViewFields->clear();
    }

    bool EntryWidgetOther::isModified()
    {
        return m_isModified;
    }

    void EntryWidgetOther::updateGUI( BibTeX::Entry::EntryType /*entryType*/, bool /*enableAll*/ )
    {
        // nothing
    }

    void EntryWidgetOther::apply( BibTeX::Entry *entry )
    {
        Settings * settings = Settings::self();
        TQStringList toBeDeleted;
        for ( TQValueList<BibTeX::EntryField*>::ConstIterator it = entry->begin(); it != entry->end(); it++ )
        {
            BibTeX::EntryField *field = *it;
            bool doDel = field->fieldType() == BibTeX::EntryField::ftUnknown;
            if ( !doDel ) continue;

            TQString ftn = field->fieldTypeName().lower();
            for ( unsigned int i = 0; doDel && i < settings->userDefinedInputFields.count(); ++i )
                doDel &= settings->userDefinedInputFields[i]->name.lower() != ftn;

            if ( doDel )
                toBeDeleted.append( ftn );
        }
        for ( TQStringList::ConstIterator it = toBeDeleted.begin(); it != toBeDeleted.end(); ++it )
            entry->deleteField( *it );

        for ( TQListViewItemIterator it( m_listViewFields ); it.current(); it++ )
        {
            ValueListViewItem *vlvi = dynamic_cast<KBibTeX::ValueListViewItem*>( it.current() );
            if ( vlvi != NULL )
            {
                BibTeX::EntryField * field = new BibTeX::EntryField( vlvi->title() );
                field->setValue( vlvi->value() );
                entry->addField( field );
            }
        }

        m_isModified = false;
    }

    void EntryWidgetOther::reset( BibTeX::Entry *entry )
    {
        m_listViewFields->clear();

        Settings * settings = Settings::self();
        for ( TQValueList<BibTeX::EntryField*>::ConstIterator it = entry->begin(); it != entry->end(); it++ )
        {
            BibTeX::EntryField *field = *it;
            bool doAdd = field->fieldType() == BibTeX::EntryField::ftUnknown;
            if ( !doAdd ) continue;

            TQString ftn = field->fieldTypeName().lower();
            for ( unsigned int i = 0; doAdd && i < settings->userDefinedInputFields.count(); ++i )
                doAdd &= settings->userDefinedInputFields[i]->name.lower() != ftn;

            if ( doAdd )
                new ValueListViewItem( field->fieldTypeName(), field->value(), m_listViewFields );
        }

        m_isModified = false;
    }

    void EntryWidgetOther::updateWarnings( BibTeX::Entry::EntryType /*entryType*/, TQListView * /*listViewWarnings*/ )
    {
        // no warnings neccessary for user fields
    }

    void EntryWidgetOther::setupGUI()
    {
        TQGridLayout * gridLayout = new TQGridLayout( this, 5, 3, KDialog::marginHint(), KDialog::spacingHint(), "gridLayout" );

        m_lineEditKey = new KLineEdit( this, "m_lineEditKey" );
        m_lineEditKey->setReadOnly( m_isReadOnly );
        gridLayout->addWidget( m_lineEditKey, 0, 1 );
        TQToolTip::add( m_lineEditKey, i18n( "Name of the user-defined field" ) );
        TQWhatsThis::add( m_lineEditKey, i18n( "The name of the user-defined field. Should only contain letters and numbers." ) );
        TQLabel *label = new TQLabel( i18n( "&Name:" ), this );
        label->setBuddy( m_lineEditKey );
        gridLayout->addWidget( label, 0, 0 );

        m_pushButtonAdd = new KPushButton( i18n( "&Add" ), this, "m_pushButtonAdd" );
        gridLayout->addWidget( m_pushButtonAdd, 0, 2 );
        m_pushButtonAdd->setIconSet( TQIconSet( SmallIcon( "add" ) ) );

        m_fieldLineEditValue = new KBibTeX::FieldLineEdit( i18n( "Value" ), KBibTeX::FieldLineEdit::itMultiLine, m_isReadOnly, this, "m_fieldLineEditValue" );
        gridLayout->addMultiCellWidget( m_fieldLineEditValue, 1, 2, 1, 2 );
        TQToolTip::add( m_fieldLineEditValue, i18n( "Content of the user-defined field" ) );
        TQWhatsThis::add( m_fieldLineEditValue, i18n( "The content of the user-defined field. May contain any text." ) );
        label = new TQLabel( i18n( "&Content:" ), this );
        label->setBuddy( m_fieldLineEditValue );
        gridLayout->addWidget( label, 1, 0 );

        TQSpacerItem* spacer = new TQSpacerItem( 20, 110, TQSizePolicy::Minimum, TQSizePolicy::Expanding );
        gridLayout->addItem( spacer, 2, 0 );

        m_listViewFields = new TDEListView( this, "m_listViewFields" );
        m_listViewFields->addColumn( i18n( "Key" ) );
        m_listViewFields->addColumn( i18n( "Value" ) );
        m_listViewFields->setAllColumnsShowFocus( true );
        m_listViewFields->setFullWidth( true );
        gridLayout->addMultiCellWidget( m_listViewFields, 3, 5, 1, 1 );

        label = new TQLabel( i18n( "&List:" ), this );
        label->setBuddy( m_listViewFields );
        label->setAlignment( TQt::AlignTop );
        gridLayout->addWidget( label, 3, 0 );

        m_pushButtonDelete = new KPushButton( i18n( "&Delete" ), this, "m_pushButtonDelete" );
        gridLayout->addWidget( m_pushButtonDelete, 3, 2 );
        m_pushButtonDelete->setIconSet( TQIconSet( SmallIcon( "delete" ) ) );

        m_pushButtonOpen = new KPushButton( i18n( "Op&en" ), this, "m_pushButtonOpen" );
        gridLayout->addWidget( m_pushButtonOpen, 4, 2 );
        m_pushButtonOpen->setIconSet( TQIconSet( SmallIcon( "document-open" ) ) );

        spacer = new TQSpacerItem( 20, 110, TQSizePolicy::Minimum, TQSizePolicy::Expanding );
        gridLayout->addItem( spacer, 5, 2 );

        m_pushButtonOpen->setEnabled( false );
        m_pushButtonAdd->setEnabled( false );
        m_pushButtonDelete->setEnabled( false );

        connect( m_listViewFields, TQ_SIGNAL( clicked( TQListViewItem*, const TQPoint&, int ) ), this, TQ_SLOT( fieldExecute( TQListViewItem* ) ) );
        connect( m_lineEditKey, TQ_SIGNAL( textChanged( const TQString& ) ), this, TQ_SLOT( updateGUI() ) );
        connect( m_fieldLineEditValue, TQ_SIGNAL( textChanged( ) ), this, TQ_SLOT( updateGUI() ) );
        connect( m_pushButtonAdd, TQ_SIGNAL( clicked( ) ), this, TQ_SLOT( addClicked( ) ) );
        connect( m_pushButtonDelete, TQ_SIGNAL( clicked( ) ), this, TQ_SLOT( deleteClicked( ) ) );
        connect( m_pushButtonOpen, TQ_SIGNAL( clicked() ), this, TQ_SLOT( openClicked() ) );
    }

    void EntryWidgetOther::updateGUI()
    {
        TQString text = m_lineEditKey->text();
        TQListViewItem * item = m_listViewFields->findItem( text, 0 ) ;
        bool contains = item != NULL;
        bool isUnknown = BibTeX::EntryField::fieldTypeFromString( text ) == BibTeX::EntryField::ftUnknown;

        if ( contains )
            m_listViewFields->setSelected( item, true );
        else
            m_listViewFields->clearSelection();

        m_pushButtonDelete->setEnabled( !m_isReadOnly && contains );
        m_pushButtonAdd->setEnabled( !m_isReadOnly && !text.isEmpty() && !m_fieldLineEditValue->isEmpty() && isUnknown );
        m_pushButtonAdd->setText( contains ? i18n( "&Apply" ) : i18n( "&Add" ) );
        m_pushButtonAdd->setIconSet( TQIconSet( SmallIcon( contains ? "apply" : "document-open" ) ) );

        bool validURL = false;
        if ( contains )
        {
            KURL url = Settings::locateFile( item->text( 1 ), m_bibtexfile->fileName, this );
            validURL = url.isValid();
            m_internalURL = url;
        }
        m_pushButtonOpen->setEnabled( validURL );
    }

    void EntryWidgetOther::fieldExecute( TQListViewItem * item )
    {
        ValueListViewItem * vlvi = dynamic_cast<KBibTeX::ValueListViewItem*>( item );
        if ( vlvi != NULL )
        {
            m_lineEditKey->setText( vlvi->title() );
            m_fieldLineEditValue->setValue( vlvi->value() );
        }
    }

    void EntryWidgetOther::addClicked()
    {
        TQString key = m_lineEditKey->text();
        TQListViewItem * item = m_listViewFields->findItem( key, 0 ) ;
        ValueListViewItem * vlvi = item != NULL ? dynamic_cast<KBibTeX::ValueListViewItem*>( item ) : NULL;

        if ( vlvi != NULL )
            vlvi->setValue( m_fieldLineEditValue->value() );
        else
            new ValueListViewItem( key, m_fieldLineEditValue->value(), m_listViewFields );

        updateGUI();

        m_isModified = true;
    }

    void EntryWidgetOther::deleteClicked()
    {
        TQListViewItem * item = m_listViewFields->findItem( m_lineEditKey->text(), 0 );

        if ( item != NULL )
        {
            delete item;
            m_lineEditKey->setText( "" );
            m_fieldLineEditValue->setValue( new BibTeX::Value() );
            updateGUI();
        }

        m_isModified = true;
    }

    void EntryWidgetOther::openClicked()
    {
        if ( m_internalURL.isValid() )
        {
            BibTeX::Value * value = m_fieldLineEditValue->value();
            Settings::openUrl( m_internalURL, this );
            delete value;
        }
        else
            m_fieldLineEditValue->setEnabled( false );
    }

    ValueListViewItem::ValueListViewItem( const TQString& title, BibTeX::Value *value, TQListView *parent )
            : TQListViewItem( parent ), m_title( title )
    {
        m_value = new BibTeX::Value( value );
        setTexts( m_title );
    }

    ValueListViewItem::~ValueListViewItem()
    {
        delete m_value;
    }

    const BibTeX::Value *ValueListViewItem::value()
    {
        return m_value;
    }

    TQString ValueListViewItem::title()
    {
        return m_title;
    }

    void ValueListViewItem::setValue( BibTeX::Value *value )
    {
        if ( value != m_value )
        {
            if ( m_value != NULL )
                delete m_value;

            if ( value != NULL )
                m_value = new BibTeX::Value( value );
            else
                m_value = new BibTeX::Value();

        }
        setTexts( m_title );
    }

    void ValueListViewItem::setTitle( const TQString &title )
    {
        m_title = title;
        setTexts( title );
    }

    void ValueListViewItem::setTexts( const TQString& title )
    {
        setText( 0, title );
        if ( m_value != NULL )
            setText( 1, m_value->text() );
    }

}
#include "entrywidgetother.moc"
