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

#include <qfile.h>
#include <qfileinfo.h>
#include <qmessagebox.h>
#include <qprocess.h>
#include <qpushbutton.h>
#include <qsettings.h>
#include <qtextedit.h>


c2bPostProcess::c2bPostProcess(const QString& fn,
                               QWidget* parent, const char* name, bool modal, WFlags fl)
        : c2bPostProcessBase(parent,name, modal,fl)
{
    connect( buttonHelp, SIGNAL( clicked() ), this, SLOT( Help() ));
    connect( buttonOpenFile, SIGNAL( clicked() ), this, SLOT( openFile() ));
    buttonOpenFile->setEnabled( FALSE );
    buttonClose->setEnabled( FALSE );
    Logs->setTextFormat( Qt::LogText );
    QSettings settings;
    settings.insertSearchPath( QSettings::Windows, WINDOWS_REGISTRY );
    PPBIBTEX_BIN = QDir::convertSeparators(
                       settings.readEntry( APP_KEY + "ppbibtexbin", APP_PPBIBTEX_BIN ));
    PPBIBTEX_ARG = settings.readEntry( APP_KEY + "ppbibtexarg", APP_PPBIBTEX_ARG );
    PPBIBTEX_ARG = PPBIBTEX_ARG.simplifyWhiteSpace();
    PPBIBTEX_EXT = settings.readEntry( APP_KEY + "ppbibtexext", APP_PPBIBTEX_EXT );

    QFile f( fn );
    if ( ! f.open( IO_ReadOnly ) )
    {
        QMessageBox::information(
            parent, tr("cb2Bib Info"),
            tr( tr("Unable to open file %1 for reading.\nError: '%2'\n\n").
                arg(fn).arg(f.errorString()) ), tr("&Continue") );
        buttonClose->setEnabled( TRUE );
        buttonClose->setFocus();
        Logs->append( tr("BibTeX Post Processing Command:\n%1 %2\n").
                      arg( PPBIBTEX_BIN ).arg( PPBIBTEX_ARG ) );
    }
    else
    {
        f.close();
        bib = fn;
        QFileInfo fi(fn);
        out = QDir::convertSeparators( fi.dirPath(TRUE) + '/' +
                                       fi.baseName() + '.' + PPBIBTEX_EXT );
        QString cargs = PPBIBTEX_ARG;
        cargs.replace( "%finput", bib );
        cargs.replace( "%foutput", out );
        Logs->append( tr("BibTeX Post Processing Command:\n%1 %2\n").
                      arg( PPBIBTEX_BIN ).arg( cargs ) );
        PProcessFile();
    }
}

c2bPostProcess::~c2bPostProcess()
{}


void c2bPostProcess::PProcessFile()
{
    // Postprocessing BibTeX
    ppBibTeX = new QProcess( this );
    if ( PPBIBTEX_BIN.endsWith( ".bat", FALSE ) )  // There is a bug in old Qts
        ppBibTeX->addArgument( "\"" + PPBIBTEX_BIN + "\"" );
    else
        ppBibTeX->addArgument( PPBIBTEX_BIN );
    QStringList arglist = QStringList::split( " ", PPBIBTEX_ARG );
    int n = arglist.count();
    for ( int i =0; i < n; i++ )
    {
        if ( arglist[i] == "%finput" )
            ppBibTeX->addArgument( bib );
        else if ( arglist[i] == "%foutput" )
            ppBibTeX->addArgument( out );
        else
            ppBibTeX->addArgument( arglist[i] );
    }
    connect( ppBibTeX, SIGNAL(readyReadStdout()), this, SLOT( AddToLogs() ) );
    connect( ppBibTeX, SIGNAL(readyReadStderr()), this, SLOT( AddToLogs() ) );
    connect( ppBibTeX, SIGNAL(processExited()), this, SLOT( conversionEnded() ) );
    if ( !ppBibTeX->start() )
    {
        disconnect( ppBibTeX, SIGNAL(readyReadStdout()), this, SLOT( AddToLogs() ) );
        disconnect( ppBibTeX, SIGNAL(readyReadStderr()), this, SLOT( AddToLogs() ) );
        disconnect( ppBibTeX, SIGNAL(processExited()), this, SLOT( conversionEnded() ) );
        Logs->append( QString("Failed to call %1.").arg( PPBIBTEX_BIN ) );
        buttonClose->setEnabled( TRUE );
        buttonClose->setFocus();
    }
}

void c2bPostProcess::conversionEnded()
{
    buttonOpenFile->setEnabled( TRUE );
    buttonClose->setEnabled( TRUE );
    buttonOpenFile->setFocus();
    Logs->append( tr( QString("\n\nBibTeX Post Processing Command Ended.") ) );
}

void c2bPostProcess::AddToLogs()
{
    while ( ppBibTeX->canReadLineStdout() )
        Logs->append( "[ppbibtex] " + ppBibTeX->readLineStdout() );
    while ( ppBibTeX->canReadLineStderr() )
        Logs->append( "[ppbibtex] " + ppBibTeX->readLineStderr() );
}

void c2bPostProcess::openFile()
{
    emit openFileRequested( out );
    close();
}

void c2bPostProcess::Help()
{
    emit helpRequested( "http://www.molspaces.com/d_cb2bib-overview.php#keyboard" );
}
