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

#include <kiconloader.h>
#include <kcombobox.h>
#include <kpushbutton.h>
#include <tdelocale.h>
#include <tdemessagebox.h>
#include <klineedit.h>
#include <tdeio/netaccess.h>
#include <kurl.h>

#include "settings.h"
#include "fileimporterbibtex.h"
#include "webqueryspireshep.h"

namespace KBibTeX
{

    const TQString WebQuerySpiresHep::mirrorNames[] = {i18n( "DESY (Germany)" ), i18n( "FNAL (U.S.A.)" ), i18n( "IHEP (Russia)" ), i18n( "Durham U (U.K.)" ), i18n( "SLAC (U.S.A.)" ), i18n( "YITP (Japan)" ), i18n( "LIPI (Indonesia)" )};
    const TQString WebQuerySpiresHep::mirrorURLs[] = {"http://www-library.desy.de/cgi-bin/spiface", "http://www-spires.fnal.gov/spires", "http://usparc.ihep.su/spires", "http://www-spires.dur.ac.uk/spires", "http://www.slac.stanford.edu/spires", "http://www.yukawa.kyoto-u.ac.jp/spires", "http://www.spires.lipi.go.id/spires"};

    WebQuerySpiresHepWidget::WebQuerySpiresHepWidget( TQWidget *parent, const char *name )
            : WebQueryWidget( parent, name )
    {
        init();

        Settings *settings = Settings::self();
        TQString value = settings->getWebQueryDefault( "SpiresHep_query" );
        value = value == TQString::null ? "" : value;
        lineEditQuery->setText( value );
        slotTextChanged( value, true );
        value = settings->getWebQueryDefault( "SpiresHep_mirror" );
        value = value == TQString::null || value.isEmpty() ? "0" : value;
        comboBoxMirror->setCurrentItem( value.toInt() );
        value = settings->getWebQueryDefault( "SpiresHep_type" );
        value = value == TQString::null || value.isEmpty() ? "0" : value;
        comboBoxType->setCurrentItem( value.toInt() );
    }

    void WebQuerySpiresHepWidget::init()
    {
        TQVBoxLayout *vLayout = new TQVBoxLayout( this, 0, KDialog::spacingHint() );

        TQHBoxLayout *hLayout = new TQHBoxLayout( );
        vLayout->addLayout( hLayout );

        comboBoxMirror = new KComboBox( false, this );
        hLayout->addWidget( comboBoxMirror );
        hLayout->setStretchFactor( comboBoxMirror, 7 );
        hLayout->addSpacing( KDialog::spacingHint() * 2 );
        for ( unsigned int i = 0; i < sizeof( WebQuerySpiresHep::mirrorNames ) / sizeof( WebQuerySpiresHep::mirrorNames[0] ); ++i )
            comboBoxMirror->insertItem( WebQuerySpiresHep::mirrorNames[i] );
        comboBoxMirror->setCurrentItem( 0 );

        TQLabel *label = new TQLabel( i18n( "Type:" ), this );
        hLayout->addWidget( label );
        hLayout->setStretchFactor( label, 1 );
        comboBoxType = new KComboBox( false, this );
        label->setBuddy( comboBoxType );
        hLayout->addWidget( comboBoxType );
        hLayout->setStretchFactor( comboBoxType, 5 );
        comboBoxType->insertItem( i18n( "raw query" ) );
        comboBoxType->insertItem( i18n( "author" ) );
        comboBoxType->insertItem( i18n( "title" ) );
        comboBoxType->insertItem( i18n( "journal" ) );
        comboBoxType->insertItem( i18n( "EPrint number" ) );
        comboBoxType->insertItem( i18n( "report number" ) );
        comboBoxType->insertItem( i18n( "keywords" ) );
        comboBoxType->setCurrentItem( 0 );

        hLayout = new TQHBoxLayout( );
        vLayout->addLayout( hLayout );
        KPushButton *clearSearchText = new KPushButton( this );
        clearSearchText->setIconSet( TQIconSet( SmallIcon( "locationbar_erase" ) ) );
        hLayout->addWidget( clearSearchText );
        label = new TQLabel( i18n( "Search &term:" ), this );
        hLayout->addWidget( label );
        lineEditQuery = new KLineEdit( this );
        hLayout->addWidget( lineEditQuery );
        label->setBuddy( lineEditQuery );
        connect( clearSearchText, TQ_SIGNAL( clicked() ), lineEditQuery, TQ_SLOT( clear() ) );
        connect( lineEditQuery, TQ_SIGNAL( textChanged( const TQString& ) ), this, TQ_SLOT( slotTextChanged( const TQString& ) ) );
        hLayout->setStretchFactor( lineEditQuery, 4 );
        TDECompletion *completionQuery = lineEditQuery->completionObject();

        m_checkBoxFetchAbstracts = new TQCheckBox( i18n( "Include abstracts from arxiv.org if available" ), this );
        vLayout->addWidget( m_checkBoxFetchAbstracts );

        connect( lineEditQuery, TQ_SIGNAL( returnPressed() ), this, TQ_SIGNAL( startSearch() ) );
        connect( lineEditQuery, TQ_SIGNAL( returnPressed( const TQString& ) ), completionQuery, TQ_SLOT( addItem( const TQString& ) ) );

        vLayout->addStretch( 1 );
    }

    WebQuerySpiresHep::WebQuerySpiresHep( TQWidget* parent ): WebQuery( parent )
    {
        m_widget = new WebQuerySpiresHepWidget( parent );
    }

    WebQuerySpiresHep::~WebQuerySpiresHep()
    {
        delete m_widget;
    }

    TQString WebQuerySpiresHep::title()
    {
        return i18n( "SPIRES-HEP" );
    }

    TQString WebQuerySpiresHep::disclaimer()
    {
        return i18n( "SPIRES-HEP Search" );
    }

    TQString WebQuerySpiresHep::disclaimerURL()
    {
        return "http://www.slac.stanford.edu/spires/";
    }

    WebQueryWidget *WebQuerySpiresHep::widget()
    {
        return m_widget;
    }

    void WebQuerySpiresHep::query()
    {
        const int maxEntries = 25;
        bool doFetchAbstracts = m_widget->m_checkBoxFetchAbstracts->isChecked();
        int mirrorIdx = m_widget->comboBoxMirror->currentItem();

        WebQuery::query();
        Settings *settings = Settings::self();
        settings->setWebQueryDefault( "SpiresHep_query", m_widget->lineEditQuery->text() );
        settings->setWebQueryDefault( "SpiresHep_mirror", TQString::number( m_widget->comboBoxMirror->currentItem() ) );
        settings->setWebQueryDefault( "SpiresHep_type", TQString::number( m_widget->comboBoxType->currentItem() ) );

        setNumStages( 1 + doFetchAbstracts ? maxEntries : 0 );

        TQString searchTerm = m_widget->lineEditQuery->text().stripWhiteSpace().replace( '$', "" );
        if ( searchTerm.isEmpty() )
        {
            setEndSearch( WebQuery::statusInvalidQuery );
            return;
        }

        switch ( m_widget->comboBoxType->currentItem() )
        {
        case 1: searchTerm = searchTerm.prepend( "fin a " ); break;
        case 2: searchTerm = searchTerm.prepend( "fin t " ); break;
        case 3: searchTerm = searchTerm.prepend( "fin j " ); break;
        case 4: searchTerm = searchTerm.prepend( "fin eprint " ); break;
        case 5: searchTerm = searchTerm.prepend( "fin r" ); break;
        case 6: searchTerm = searchTerm.prepend( "fin k" ); break;
        default: ;// nothing
        }

        KURL url = KURL( TQString( "%1/find/hep/www?rawcmd=%2&FORMAT=WWWBRIEFBIBTEX&SEQUENCE=" ).arg( mirrorURLs[mirrorIdx] ).arg( searchTerm.replace( "%", "%25" ).replace( "+", "%2B" ).replace( " ", "%20" ).replace( "#", "%23" ).replace( "&", "%26" ).replace( "?", "%3F" ) ) );
        tqDebug( "url=%s", url.prettyURL().latin1() );

        BibTeX::File *tmpBibFile = downloadBibTeXFile( url );
        if ( tmpBibFile != NULL && !m_aborted )
        {
            int count = 0;
            for ( BibTeX::File::ElementList::iterator it = tmpBibFile->begin(); count < maxEntries && it != tmpBibFile->end(); ++it, ++count )
            {
                BibTeX::Entry *entry = dynamic_cast<BibTeX::Entry*>( *it );
                if ( doFetchAbstracts )
                {
                    fetchArxivAbstract( entry );
                    enterNextStage();
                }
                if ( entry != NULL )
                    emit foundEntry( new BibTeX::Entry( entry ), false );
            }

            setEndSearch( WebQuery::statusSuccess );
        }
        else if ( !m_aborted )
        {
            TQString message = TDEIO::NetAccess::lastErrorString();
            if ( message.isEmpty() )
                message.prepend( '\n' );
            message.prepend( TQString( i18n( "Querying database '%1' failed." ) ).arg( title() ) );
            KMessageBox::error( m_parent, message );
            setEndSearch( WebQuery::statusError );
        }
        else
            setEndSearch( WebQuery::statusAborted );

        if ( tmpBibFile != NULL )
            delete tmpBibFile;
    }

    void WebQuerySpiresHep::fetchArxivAbstract( BibTeX::Entry *entry )
    {
        BibTeX::EntryField *field = NULL;
        BibTeX::Value *value = NULL;
        TQString eprint = (( field = entry->getField( "eprint" ) ) ) && (( value = field->value() ) ) ? value->text() : TQString::null;
        TQString archivePrefix = (( field = entry->getField( "archivePrefix" ) ) ) && (( value = field->value() ) ) ? value->text() : TQString::null;

        if ( archivePrefix == "arXiv" && !eprint.isNull() )
        {
            KURL absURL( TQString( "http://arxiv.org/abs/" ).append( eprint ) );
            TQString abstract = download( absURL );
            int p = abstract.find( "Abstract:</span>" );
            if ( p > -1 )
            {
                int p2 = abstract.find( "</", p + 14 );
                abstract = abstract.mid( p + 16, p2 - p - 16 ).simplifyWhiteSpace();
                BibTeX::EntryField * field = new BibTeX::EntryField( BibTeX::EntryField::ftAbstract );
                entry->addField( field );
                field->setValue( new BibTeX::Value( abstract ) );

                field = new BibTeX::EntryField( "pdf" );
                entry->addField( field );
                field->setValue( new BibTeX::Value( TQString( "http://arxiv.org/pdf/" ).append( eprint ) ) );

                field = new BibTeX::EntryField( BibTeX::EntryField::ftURL );
                entry->addField( field );
                field->setValue( new BibTeX::Value( TQString( "http://arxiv.org/abs/" ).append( eprint ) ) );
            }
        }
    }
}
#include "webqueryspireshep.moc"
