/***************************************************************************
 *   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 <qfile.h>
#include <qapplication.h>
#include <qlayout.h>
#include <qlabel.h>
#include <qcheckbox.h>

#include <kiconloader.h>
#include <kcombobox.h>
#include <kpushbutton.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <klineedit.h>
#include <kio/netaccess.h>
#include <kurl.h>

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

namespace KBibTeX
{

    const QString 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 QString 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( QWidget *parent, const char *name )
            : WebQueryWidget( parent, name )
    {
        init();

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

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

        QHBoxLayout *hLayout = new QHBoxLayout( );
        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 );

        QLabel *label = new QLabel( 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 QHBoxLayout( );
        vLayout->addLayout( hLayout );
        KPushButton *clearSearchText = new KPushButton( this );
        clearSearchText->setIconSet( QIconSet( SmallIcon( "locationbar_erase" ) ) );
        hLayout->addWidget( clearSearchText );
        label = new QLabel( i18n( "Search &term:" ), this );
        hLayout->addWidget( label );
        lineEditQuery = new KLineEdit( this );
        hLayout->addWidget( lineEditQuery );
        label->setBuddy( lineEditQuery );
        connect( clearSearchText, SIGNAL( clicked() ), lineEditQuery, SLOT( clear() ) );
        connect( lineEditQuery, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotTextChanged( const QString& ) ) );
        hLayout->setStretchFactor( lineEditQuery, 4 );
        KCompletion *completionQuery = lineEditQuery->completionObject();

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

        connect( lineEditQuery, SIGNAL( returnPressed() ), this, SIGNAL( startSearch() ) );
        connect( lineEditQuery, SIGNAL( returnPressed( const QString& ) ), completionQuery, SLOT( addItem( const QString& ) ) );

        vLayout->addStretch( 1 );
    }

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

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

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

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

    QString 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", QString::number( m_widget->comboBoxMirror->currentItem() ) );
        settings->setWebQueryDefault( "SpiresHep_type", QString::number( m_widget->comboBoxType->currentItem() ) );

        setNumStages( 1 + doFetchAbstracts ? maxEntries : 0 );

        QString 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( QString( "%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" ) ) );
        qDebug( "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 )
        {
            QString message = KIO::NetAccess::lastErrorString();
            if ( message.isEmpty() )
                message.prepend( '\n' );
            message.prepend( QString( 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;
        QString eprint = (( field = entry->getField( "eprint" ) ) ) && (( value = field->value() ) ) ? value->text() : QString::null;
        QString archivePrefix = (( field = entry->getField( "archivePrefix" ) ) ) && (( value = field->value() ) ) ? value->text() : QString::null;

        if ( archivePrefix == "arXiv" && !eprint.isNull() )
        {
            KURL absURL( QString( "http://arxiv.org/abs/" ).append( eprint ) );
            QString 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( QString( "http://arxiv.org/pdf/" ).append( eprint ) ) );

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