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

#include <qfile.h>
#include <qmessagebox.h>
#include <qprocess.h>
#include <qstatusbar.h>
#include <qtimer.h>


c2bBibPreParser::c2bBibPreParser(c2bSettings *st, cb2bibbase *c2bMain,
                                 QObject *parent, const char *name)
        : QObject(parent, name)
{
    c2b = c2bMain;
    s = st;
    viewLog = new c2bPreParserLogViewer( s, c2b );
    connect( viewLog, SIGNAL(helpRequested(const QString&)),
             this, SIGNAL(helpRequested(const QString&)) );
    inp_file = QDir::homeDirPath() + QDir::separator() + "cb2bib_clipborad_inp";
    out_file = QDir::homeDirPath() + QDir::separator() + "cb2bib_clipborad_out";
}

c2bBibPreParser::~c2bBibPreParser()
{
    delete viewLog;
}


void c2bBibPreParser::preParseItem( const QString& cb )
{
    inp_string = cb + "\n";
    QFile file( inp_file );
    if ( file.open( IO_WriteOnly ) )
    {
        QTextStream stream( &file );
        stream << inp_string;
        file.close();
        preProcess();
    }
    else
        QMessageBox::warning( c2b, tr("cb2Bib Info"),
                              tr( QString( "Unable to open file %1 for writing.\n"
                                           "Error: '%2'\n" ).arg(inp_file).arg(file.errorString()) ),
                              tr( "&Continue" ) );
}

void c2bBibPreParser::preProcess()
{
    // External Preprocessing
    c2b->statusBar()->message( tr( "External Parsing started." ), MESSAGE_TIME );
    preParser = new QProcess( this );
    if ( s->m_preparser_bin.endsWith( ".bat", FALSE ) )  // There is a bug in old Qts
        preParser->addArgument( "\"" + s->m_preparser_bin + "\"" );
    else
        preParser->addArgument( s->m_preparser_bin );
    preParser->addArgument( inp_file );
    preParser->addArgument( out_file );

    connect( preParser, SIGNAL(processExited()), this, SLOT( conversionEnded() ) );
    if ( preParser->start() )
        QTimer::singleShot( MESSAGE_TIME, preParser, SLOT(kill()) );  // It's 1 ref; it should be fast...
    else
    {
        disconnect( preParser, SIGNAL(processExited()), this, SLOT( conversionEnded() ) );
        c2b->statusBar()->message(
            tr("Failed to call %1.").arg( s->m_preparser_bin ), MESSAGE_TIME );
    }
}

void c2bBibPreParser::conversionEnded()
{
    disconnect( preParser, SIGNAL(processExited()), this, SLOT( conversionEnded() ) );
    if ( s->m_preparser_show_log )
        viewLog->readLog( preParser );
    QFile ifile( inp_file );
    ifile.remove();
    QFile ofile( out_file );
    out_string = "";
    if ( ofile.open( IO_ReadOnly ) )
    {
        QTextStream stream( &ofile );
        while ( !stream.atEnd() )
            out_string += stream.readLine()+"\n";
        ofile.remove();
    }
    if( out_string.isEmpty() )
    {
        c2b->statusBar()->message(
            tr( "External Parsing ended. Input string remained unchanged." ), MESSAGE_TIME );
        emit preParserDataAvailable( inp_string );
    }
    else
    {
        c2b->statusBar()->message( tr( "External Parsing ended." ), MESSAGE_TIME );
        emit preParserDataAvailable( out_string );
    }
    if ( s->m_preparser_show_log )
    {
        viewLog->append( tr("Input[\n%1]\n").arg( inp_string ) );
        viewLog->append( tr("Output[\n%1]\n").arg( out_string ) );
        viewLog->exec();
    }
}
