/***************************************************************************
 *   Copyright (C) 2004-2006 by Pere Constans
 *   constans@molspaces.com
 *   cb2Bib version 0.6.1
 *   See LICENSE file that comes with this distribution
 ***************************************************************************/
#include "pdfimport.h"
#include "c2bsettings.h"

#include <qdir.h>
#include <qdragobject.h>
#include <qfiledialog.h>
#include <qlistview.h>
#include <qprocess.h>
#include <qpushbutton.h>
#include <qtextedit.h>


PDFImport::PDFImport(c2bSettings* settings, QWidget* parent, const char* name, WFlags fl)
        : PDFImportBase(parent,name,fl)
{
    s = settings;
    m_pdf_file = "";
    m_text_file = QDir::homeDirPath() + QDir::separator() + "cb2bib_pdfconv.tmp";
    m_pdf_dir = QDir::homeDirPath() + QDir::separator();
    buttonProcess->setEnabled( FALSE );
    Logs->setTextFormat( Qt::LogText );
    Logs->append( QString("PDF to Text converter: %1\nArguments: %2\n").arg( s->PDF2TXT_BIN ).arg( s->PDF2TXT_ARG ) );
    Logs->append( QString("See cb2Bib install directory for demo PDFImport files.\n") );
    connect( buttonHelp, SIGNAL( clicked() ), this, SLOT( help() ));
    connect( buttonSelectFiles, SIGNAL( clicked() ), this, SLOT( selectFiles() ));
    connect( buttonProcess, SIGNAL( clicked() ), this, SLOT( processOneFile() ));
}

PDFImport::~PDFImport()
{}

void PDFImport::processOneFile()
{
    // Converting PDF to Text

    buttonProcess->setEnabled( FALSE );
    if ( PDFlist->currentItem() == 0 )
        return;
    m_pdf_file = PDFlist->currentItem()->text(0);
    pdf2txt = new QProcess( this );
    pdf2txt_name = QFileInfo( s->PDF2TXT_BIN ).fileName();
    pdf2txt->addArgument( s->PDF2TXT_BIN );
    QStringList arglist = QStringList::split( " ", s->PDF2TXT_ARG );
    int n = arglist.count();
    for ( int i =0; i < n; i++ )
        pdf2txt->addArgument( arglist[i] );
    pdf2txt->addArgument( m_pdf_file );
    pdf2txt->addArgument( m_text_file );

    connect( pdf2txt, SIGNAL(readyReadStdout()), this, SLOT(addToLog()) );
    connect( pdf2txt, SIGNAL(readyReadStderr()), this, SLOT(addToLog()) );
    connect( pdf2txt, SIGNAL(processExited()), this, SLOT(processEnded()) );
    if ( pdf2txt->start() )
        delete PDFlist->currentItem();
    else
    {
        delete pdf2txt;
        Logs->append( QString("[cb2bib] Failed to call %1.").arg(s->PDF2TXT_BIN) );
    }
}

void PDFImport::processNext()
{
    if ( PDFlist->currentItem() == 0 )
        return;
    if( s->m_automatic_pdfimport )
        processOneFile();
}

void PDFImport::addToLog()
{
    while ( pdf2txt->canReadLineStdout() )
        Logs->append( "[" + pdf2txt_name + "] " + pdf2txt->readLineStdout() );
    while ( pdf2txt->canReadLineStderr() )
        Logs->append( "[" + pdf2txt_name + "] " + pdf2txt->readLineStderr() );
}

void PDFImport::processEnded()
{
    QString text = "";
    QFile file( m_text_file );
    if ( file.open( IO_ReadOnly ) )
    {
        QTextStream stream( &file );
        text = stream.read();
        file.remove();
    }
    if( pdf2txt->normalExit() && !text.isEmpty() )
    {
        Logs->append( QString("[cb2bib] Conversion completed for file %1.").arg(m_pdf_file) );
        emit textProcessed( text );
        emit fileProcessed( m_pdf_file );
    }
    else
        Logs->append( QString("[cb2bib] Conversion failed for file %1.").arg(m_pdf_file) );
    delete pdf2txt;
    buttonProcess->setEnabled( PDFlist->currentItem() != 0 );
}

void PDFImport::dropEvent( QDropEvent *e )
{
    QStringList fns;
    if ( QUriDrag::decodeLocalFiles(e, fns) )
    {
        QStringList::Iterator it = fns.begin();
        while ( it != fns.end() )
        {
            new QListViewItem( PDFlist, *it );
            it++;
        }
        buttonProcess->setEnabled( TRUE );
    }
    else
    {
        e->ignore();
        return;
    }
}

void PDFImport::dragEnterEvent( QDragEnterEvent *e )
{
    e->accept( QUriDrag::canDecode( e ) );
}

void PDFImport::selectFiles()
{
    QStringList fns = QFileDialog::getOpenFileNames("Portable Document Format (*.pdf);;All (*)", m_pdf_dir,
                      this, "open files dialog", "Select PDF files" );
    if( fns.isEmpty() )
        return;
    QStringList::Iterator it = fns.begin();
    while ( it != fns.end() )
    {
        new QListViewItem( PDFlist, *it );
        it++;
    }
    buttonProcess->setEnabled( TRUE );
}

void PDFImport::help()
{
    emit helpRequested( "http://www.molspaces.com/d_cb2bib-overview.php#c2bbuttons" );
}
