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

#include <kpushbutton.h>
#include <kdialog.h>
#include <tdelocale.h>
#include <tdefiledialog.h>
#include <kurl.h>
#include <kurllabel.h>
#include <kiconloader.h>
#include <tdepopupmenu.h>

#include "fieldlineedit.h"
#include "settings.h"
#include "entrywidgetexternal.h"

namespace KBibTeX
{

    const int EntryWidgetExternal::m_menuIdCurrentDirectory = 8192;
    const int EntryWidgetExternal::m_menuIdPreviousDirectory = 8191;
    TQString EntryWidgetExternal::m_previousDirectory = TQString::null;

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

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

    bool EntryWidgetExternal::isModified()
    {
        return m_fieldLineEditURL->isModified() || m_fieldLineEditDoi->isModified() || m_fieldLineEditLocalFile->isModified();
    }

    void EntryWidgetExternal::updateGUI( BibTeX::Entry::EntryType entryType, bool enableAll )
    {
        bool enableWidget = enableAll || BibTeX::Entry::getRequireStatus( entryType, BibTeX::EntryField::ftURL ) != BibTeX::Entry::frsIgnored;
        m_fieldLineEditURL->setEnabled( enableWidget );

        enableWidget = enableAll || BibTeX::Entry::getRequireStatus( entryType, BibTeX::EntryField::ftDoi ) != BibTeX::Entry::frsIgnored;
        m_fieldLineEditDoi->setEnabled( enableWidget );

        enableWidget = enableAll || BibTeX::Entry::getRequireStatus( entryType, BibTeX::EntryField::ftLocalFile ) != BibTeX::Entry::frsIgnored;
        m_fieldLineEditLocalFile->setEnabled( enableWidget );
        m_pushButtonBrowseLocalFile->setEnabled( !m_isReadOnly && enableWidget );

        updateGUI();
    }

    void EntryWidgetExternal::apply( BibTeX::Entry *entry )
    {
        BibTeX::Value * value = m_fieldLineEditURL->value();
        setValue( entry, BibTeX::EntryField::ftURL, value );
        delete value;

        value = m_fieldLineEditDoi->value();
        setValue( entry, BibTeX::EntryField::ftDoi, value );
        delete value;

        value = m_fieldLineEditLocalFile->value();
        setValue( entry, BibTeX::EntryField::ftLocalFile, value );
        delete value;
    }

    void EntryWidgetExternal::reset( BibTeX::Entry *entry )
    {
        disconnect( m_fieldLineEditURL, TQ_SIGNAL( textChanged() ), this, TQ_SLOT( updateGUI() ) );
        disconnect( m_fieldLineEditDoi, TQ_SIGNAL( textChanged() ), this, TQ_SLOT( updateGUI() ) );
        disconnect( m_fieldLineEditLocalFile, TQ_SIGNAL( textChanged() ), this, TQ_SLOT( updateGUI() ) );


        BibTeX::EntryField * field = entry->getField( BibTeX::EntryField::ftURL );
        m_fieldLineEditURL->setValue( field != NULL ? field->value() : NULL );

        field = entry->getField( BibTeX::EntryField::ftDoi );
        m_fieldLineEditDoi->setValue( field != NULL ? field->value() : NULL );

        field = entry->getField( BibTeX::EntryField::ftLocalFile );
        m_fieldLineEditLocalFile->setValue( field != NULL ? field->value() : NULL );

        updateGUI();

        connect( m_fieldLineEditURL, TQ_SIGNAL( textChanged() ), this, TQ_SLOT( updateGUI() ) );
        connect( m_fieldLineEditDoi, TQ_SIGNAL( textChanged() ), this, TQ_SLOT( updateGUI() ) );
        connect( m_fieldLineEditLocalFile, TQ_SIGNAL( textChanged() ), this, TQ_SLOT( updateGUI() ) );
    }

    void EntryWidgetExternal::updateWarnings( BibTeX::Entry::EntryType entryType, TQListView *listViewWarnings )
    {
        addMissingWarning( entryType, BibTeX::EntryField::ftURL, m_fieldLineEditURL->caption(), !m_fieldLineEditURL->isEmpty(), m_fieldLineEditURL, listViewWarnings );

        addMissingWarning( entryType, BibTeX::EntryField::ftDoi, m_fieldLineEditDoi->caption(), !m_fieldLineEditDoi->isEmpty(), m_fieldLineEditDoi, listViewWarnings );

        addMissingWarning( entryType, BibTeX::EntryField::ftLocalFile, m_fieldLineEditDoi->caption(), !m_fieldLineEditDoi->isEmpty(), m_fieldLineEditLocalFile, listViewWarnings );

        addFieldLineEditWarning( m_fieldLineEditURL, m_fieldLineEditURL->caption(), listViewWarnings );

        addFieldLineEditWarning( m_fieldLineEditDoi, m_fieldLineEditDoi->caption(), listViewWarnings );

        updateGUI();
    }

    void EntryWidgetExternal::openURL()
    {
        BibTeX::Value * value = m_fieldLineEditURL->value();
        KURL url = Settings::locateFile( value->text(), m_bibtexfile->fileName, this );
        if ( url.isValid() )
            Settings::openUrl( url, this );
        else
            m_pushButtonOpenURL->setEnabled( false );
    }

    void EntryWidgetExternal::openURL( const TQString &url )
    {
        Settings::openUrl( KURL( url ), this );
    }

    void EntryWidgetExternal::openDoi()
    {
        BibTeX::Value * value = m_fieldLineEditDoi->value();
        KURL url = Settings::doiURL( value->text() );
        if ( url.isValid() )
            Settings::openUrl( url, this );
        else
            m_pushButtonOpenDoi->setEnabled( false );
    }

    void EntryWidgetExternal::openLocalFile()
    {
        BibTeX::Value * value = m_fieldLineEditLocalFile->value();
        KURL url = Settings::locateFile( value->text(), m_bibtexfile->fileName, this );
        if ( url.isValid() )
            Settings::openUrl( url, this );
        else
            m_pushButtonOpenLocalFile->setEnabled( false );
    }

    void EntryWidgetExternal::browseLocalFile( int id )
    {
        Settings * settings = Settings::self();
        TQString startDir = TQString::null;
        if ( id == m_menuIdPreviousDirectory && m_previousDirectory != TQString::null )
            startDir = m_previousDirectory;
        else if ( settings->editing_DocumentSearchPaths.size() > ( unsigned int )id )
            startDir = *settings->editing_DocumentSearchPaths.at( id );
        else
            startDir = TQDir::currentDirPath();
        TQString filename = KFileDialog::getOpenFileName( startDir );

        if ( !filename.isEmpty() )
        {
            /** if the user started browsing for files from a search path,
            * remove this search path prefix from the absolute path returned
            * by the file open dialog.                                               */
            if ( id >= 0 && filename.startsWith( startDir ) )
            {
                int len = startDir.length();
                if ( startDir == "/" )
                    len = 0;
                else if ( !startDir.endsWith( "/" ) )
                    ++len;
                filename = filename.mid( len );
            }

            BibTeX::Value * value = new BibTeX::Value();
            value->items.append( new BibTeX::PlainText( filename ) );
            m_fieldLineEditLocalFile->setValue( value );

            if ( m_previousDirectory == TQString::null )
            {
                TQPopupMenu *menu = m_pushButtonBrowseLocalFile->popup();
                menu->insertItem( TQIconSet( SmallIcon( "favorite" ) ), i18n( "Previously used directory" ), m_menuIdPreviousDirectory, 2 );
            }
            TQFileInfo fileInfo( filename );
            m_previousDirectory = fileInfo.dirPath( true );
        }
    }

    void EntryWidgetExternal::updateGUI()
    {
        BibTeX::Value * value = m_fieldLineEditURL->value();
        m_pushButtonOpenURL->setEnabled( value != NULL && Settings::locateFile( value->text(), m_bibtexfile->fileName, this ).isValid() );

        value = m_fieldLineEditLocalFile->value();
        m_pushButtonOpenLocalFile->setEnabled( value != NULL && Settings::locateFile( value->text(), m_bibtexfile->fileName, this ).isValid() );

        value = m_fieldLineEditDoi->value();
        m_pushButtonOpenDoi->setEnabled( value != NULL && Settings::doiURL( value->text() ).isValid() );
    }

    void EntryWidgetExternal::setupGUI()
    {
        Settings * settings = Settings::self();

        TQGridLayout * gridLayout = new TQGridLayout( this, 5, 3, KDialog::marginHint(), KDialog::spacingHint(), "gridLayout" );
        gridLayout->setRowStretch( 4, 10 );

        TQLabel *label = new TQLabel( TQString( "%1:" ).arg( i18n( "URL" ) ), this );
        gridLayout->addWidget( label, 0, 0 );
        m_fieldLineEditURL = new KBibTeX::FieldLineEdit( i18n( "URL" ), KBibTeX::FieldLineEdit::itSingleLine, m_isReadOnly, this, "m_fieldLineEditURL" );
        m_fieldLineEditURL->setFieldType( BibTeX::EntryField::ftURL );
        gridLayout->addWidget( m_fieldLineEditURL, 0, 1 );
        label->setBuddy( m_fieldLineEditURL );
        connect( m_fieldLineEditURL, TQ_SIGNAL( textChanged() ), this, TQ_SLOT( updateGUI() ) );

        m_pushButtonOpenURL = new KPushButton( this );
        gridLayout->addWidget( m_pushButtonOpenURL, 0, 2 );
        m_pushButtonOpenURL->setIconSet( TQIconSet( SmallIcon( "document-open" ) ) );
        m_pushButtonOpenURL->setSizePolicy( TQSizePolicy::Minimum, TQSizePolicy::Minimum );
        TQToolTip::add( m_pushButtonOpenURL, TQString( i18n( "Open %1" ) ).arg( i18n( "URL" ) ) );
        connect( m_pushButtonOpenURL, TQ_SIGNAL( clicked() ), this, TQ_SLOT( openURL() ) );

        KURLLabel *urllabel = new KURLLabel( "http://www.doi.org/", TQString( "%1:" ).arg( i18n( "DOI" ) ), this );
        TQToolTip::add( urllabel, i18n( "Digital Object Identifier" ) );
        urllabel->setFocusPolicy( TQWidget::NoFocus );
        gridLayout->addWidget( urllabel, 1, 0 );
        m_fieldLineEditDoi = new KBibTeX::FieldLineEdit( i18n( "DOI" ), KBibTeX::FieldLineEdit::itSingleLine, m_isReadOnly, this, "m_fieldLineEditDoi" );
        m_fieldLineEditDoi->setFieldType( BibTeX::EntryField::ftDoi );
        gridLayout->addWidget( m_fieldLineEditDoi, 1, 1 );
        urllabel->setBuddy( m_fieldLineEditDoi );
        connect( m_fieldLineEditDoi, TQ_SIGNAL( textChanged() ), this, TQ_SLOT( updateGUI() ) );
        connect( urllabel, TQ_SIGNAL( leftClickedURL( const TQString& ) ), this, TQ_SLOT( openURL( const TQString& ) ) );

        m_pushButtonOpenDoi = new KPushButton( this );
        gridLayout->addWidget( m_pushButtonOpenDoi, 1, 2 );
        m_pushButtonOpenDoi->setIconSet( TQIconSet( SmallIcon( "document-open" ) ) );
        m_pushButtonOpenDoi->setSizePolicy( TQSizePolicy::Minimum, TQSizePolicy::Minimum );
        TQToolTip::add( m_pushButtonOpenDoi, i18n( "Open DOI" ) );
        connect( m_pushButtonOpenDoi, TQ_SIGNAL( clicked() ), this, TQ_SLOT( openDoi() ) );

        label = new TQLabel( TQString( "%1:" ).arg( i18n( "Local File" ) ), this );
        gridLayout->addWidget( label, 2, 0 );
        m_fieldLineEditLocalFile = new KBibTeX::FieldLineEdit( i18n( "Local File" ), KBibTeX::FieldLineEdit::itSingleLine, m_isReadOnly, this, "m_fieldLineEditLocalFile" );
        m_fieldLineEditLocalFile->setFieldType( BibTeX::EntryField::ftLocalFile );
        gridLayout->addWidget( m_fieldLineEditLocalFile, 2, 1 );
        label->setBuddy( m_fieldLineEditLocalFile );
        connect( m_fieldLineEditLocalFile, TQ_SIGNAL( textChanged() ), this, TQ_SLOT( updateGUI() ) );

        m_pushButtonOpenLocalFile = new KPushButton( this );
        gridLayout->addWidget( m_pushButtonOpenLocalFile, 2, 2 );
        m_pushButtonOpenLocalFile->setIconSet( TQIconSet( SmallIcon( "document-open" ) ) );
        m_pushButtonOpenLocalFile->setSizePolicy( TQSizePolicy::Minimum, TQSizePolicy::Minimum );
        TQToolTip::add( m_pushButtonOpenLocalFile, TQString( i18n( "Open %1" ) ).arg( i18n( "Local File" ) ) );
        connect( m_pushButtonOpenLocalFile, TQ_SIGNAL( clicked() ), this, TQ_SLOT( openLocalFile() ) );

        TQWidget *container = new TQWidget( this );
        TQHBoxLayout *containerLayout = new TQHBoxLayout( container );
        gridLayout->addWidget( container, 3, 1 );
        m_pushButtonBrowseLocalFile = new KPushButton( i18n( "&Browse..." ), container );
        TQToolTip::add( m_pushButtonBrowseLocalFile, i18n( "Browse for a local file" ) );
        m_pushButtonBrowseLocalFile->setSizePolicy( TQSizePolicy::Minimum, TQSizePolicy::Minimum );
        containerLayout->addWidget( m_pushButtonBrowseLocalFile );
        containerLayout->addStretch( 10 );
        m_pushButtonBrowseLocalFile->setIconSet( TQIconSet( SmallIcon( "document-open" ) ) );

        TDEPopupMenu *menu = new TDEPopupMenu( m_pushButtonBrowseLocalFile );
        menu->insertTitle( i18n( "Select base directory" ) );
        menu->insertItem( TQIconSet( SmallIcon( "favorite" ) ), i18n( "Current directory" ), m_menuIdCurrentDirectory );
        if ( m_previousDirectory != TQString::null )
            menu->insertItem( TQIconSet( SmallIcon( "favorite" ) ), i18n( "Previously used directory" ), m_menuIdPreviousDirectory );
        if ( !settings->editing_DocumentSearchPaths.isEmpty() )
        {
            menu->insertSeparator();
            int i = 0;
            for ( TQStringList::Iterator it = settings->editing_DocumentSearchPaths.begin(); it != settings->editing_DocumentSearchPaths.end(); ++it, ++i )
                menu->insertItem( TQIconSet( SmallIcon( "folder" ) ), *it, i );
        }
        m_pushButtonBrowseLocalFile->setPopup( menu );
        connect( menu, TQ_SIGNAL( activated( int ) ), this, TQ_SLOT( browseLocalFile( int ) ) );
    }
}
#include "entrywidgetexternal.moc"
