/***************************************************************************
 *   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 <tqdir.h>
#include <tqstringlist.h>
#include <tqapplication.h>
#include <tqbuffer.h>
#include <tqprocess.h>
#include <tqwaitcondition.h>

#include "fileexporterbibtex.h"
#include "fileexporterbibutils.h"

namespace BibTeX
{

    FileExporterBibUtils::FileExporterBibUtils( BibTeX::File::FileFormat outputFormat )
            : FileExporter(), m_outputFormat( outputFormat ), m_bibTeXExporter( new FileExporterBibTeX() )
    {
        m_bibTeXExporter->setEncoding( "utf-8" );
        m_processBuffer = new TQBuffer();
    }

    FileExporterBibUtils::~FileExporterBibUtils()
    {
        delete m_processBuffer;
        delete m_bibTeXExporter;
    }

    bool FileExporterBibUtils::save( TQIODevice* iodevice, const Element* element, TQStringList* errorLog )
    {
        m_cancelFlag = false;
        TQBuffer bibBuffer;
        if ( !toBuffer( element, &bibBuffer, errorLog ) )
            return false;
        if ( !bufferToXMLbuffer( &bibBuffer ) || m_cancelFlag )
            return false;
        return !m_cancelFlag && xmlBufferToIOdevice( iodevice );
    }

    bool FileExporterBibUtils::save( TQIODevice* iodevice, const File* bibtexfile, TQStringList* errorLog )
    {
        emit progress( 0, 3 );
        m_cancelFlag = false;
        TQBuffer bibBuffer;
        if ( !toBuffer( bibtexfile, &bibBuffer, errorLog ) )
            return false;
        emit progress( 1, 3 );
        if ( m_cancelFlag || !bufferToXMLbuffer( &bibBuffer ) )
            return false;
        emit progress( 2, 3 );
        if ( m_cancelFlag || !xmlBufferToIOdevice( iodevice ) )
            return false;
        emit progress( 3, 3 );
        return !m_cancelFlag;
    }

    void FileExporterBibUtils::cancel()
    {
        m_bibTeXExporter->cancel();
        m_cancelFlag = true;
    }

    bool FileExporterBibUtils::toBuffer( const File *bibFile, TQBuffer *buffer, TQStringList* errorLog )
    {
        buffer->open( IO_WriteOnly );
        bool result = m_bibTeXExporter->save( buffer, bibFile, errorLog );
        buffer->close();
        return result;
    }

    bool FileExporterBibUtils::toBuffer( const Element *bibElement, TQBuffer *buffer, TQStringList* errorLog )
    {
        buffer->open( IO_WriteOnly );
        bool result = m_bibTeXExporter->save( buffer, bibElement, errorLog );
        buffer->close();
        return result;
    }

    bool FileExporterBibUtils::bufferToXMLbuffer( TQBuffer *bibBuffer )
    {
        TQWaitCondition wc;

        m_processBuffer->open( IO_WriteOnly );
        m_waiting = true;
        m_process = new TQProcess( TQStringList::split( ' ', "bib2xml -i utf8" ) );
        connect( m_process, TQ_SIGNAL( processExited() ), this, TQ_SLOT( wakeUp() ) );
        connect( m_process, TQ_SIGNAL( readyReadStdout() ), this, TQ_SLOT( slotReadyStdout() ) );
        connect( m_process, TQ_SIGNAL( readyReadStderr() ), this, TQ_SLOT( slotReadyStderr() ) );

        m_process->start();
        if ( m_process->isRunning() )
        {
            bibBuffer->open( IO_ReadOnly );
            m_process->writeToStdin( bibBuffer->readAll() );
            tqApp->processEvents();
            m_process->closeStdin();
            bibBuffer->close();

            int nothingHappens = 20;
            while ( m_waiting )
            {
                wc.wait( 250 );
                tqApp->processEvents();
                --nothingHappens;
            }

            if ( nothingHappens <= 0 )
                m_process->kill();

            if ( !m_process->normalExit() )
            {
                tqDebug( "%s did not exit in a clean fashion", m_process->arguments()[0].latin1() );
                delete m_process;
                return false;
            }
        }
        else
        {
            tqDebug( "%s did not start", m_process->arguments()[0].latin1() );
            delete m_process;
            return false;
        }

        m_processBuffer->close();

        delete m_process;
        return true;
    }

    bool FileExporterBibUtils::xmlBufferToIOdevice( TQIODevice *iodevice )
    {
        TQWaitCondition wc;
        m_waiting = true;

        m_process = NULL;
        switch ( m_outputFormat )
        {
        case BibTeX::File::formatISI:
            m_process = new TQProcess( TQStringList::split( ' ', "xml2isi" ) );
            break;
        case BibTeX::File::formatWordBib:
            m_process = new TQProcess( TQStringList::split( ' ', "xml2wordbib" ) );
            break;
        case BibTeX::File::formatAds:
            m_process = new TQProcess( TQStringList::split( ' ', "xml2ads" ) );
            break;
        case BibTeX::File::formatEndNote:
            m_process = new TQProcess( TQStringList::split( ' ', "xml2end" ) );
            break;
        case BibTeX::File::formatRIS:
            m_process = new TQProcess( TQStringList::split( ' ', "xml2ris" ) );
            break;
        case BibTeX::File::formatMODS:
            /* m_process = NULL; */
            break;
        default:
            tqDebug( "Cannot handle output format %i", m_outputFormat );
            return false;
        }

        if ( m_process != NULL )
        {
            connect( m_process, TQ_SIGNAL( processExited() ), this, TQ_SLOT( wakeUp() ) );
            connect( m_process, TQ_SIGNAL( readyReadStdout() ), this, TQ_SLOT( slotReadyStdout() ) );
            connect( m_process, TQ_SIGNAL( readyReadStderr() ), this, TQ_SLOT( slotReadyStderr() ) );

            if ( m_process->start() )
            {
                TQBuffer *tempBuffer = m_processBuffer;
                m_processBuffer = new TQBuffer();

                tempBuffer->open( IO_ReadOnly );
                m_process->writeToStdin( tempBuffer->readAll() );
                tqApp->processEvents();
                m_process->closeStdin();
                tempBuffer->close();

                m_processBuffer->open( IO_WriteOnly );
                int nothingHappens = 20;
                while ( m_waiting )
                {
                    wc.wait( 250 );
                    tqApp->processEvents();
                    --nothingHappens;
                }
                m_processBuffer->close();

                delete tempBuffer;

                if ( nothingHappens <= 0 )
                    m_process->kill();

                if ( ! m_process->normalExit() )
                {
                    delete m_process;
                    return false;
                }

                m_processBuffer->open( IO_ReadOnly );
                iodevice->writeBlock( m_processBuffer->buffer() );
                m_processBuffer->close();

                delete m_process;
            }
            else
            {
                tqDebug( "%s did not start", m_process->arguments()[0].latin1() );
                delete m_process;
                return false;
            }
        }
        else
        {
            m_processBuffer->open( IO_ReadOnly );
            iodevice->writeBlock( m_processBuffer->buffer() );
            m_processBuffer->close();
        }

        return true;
    }

    void FileExporterBibUtils::wakeUp()
    {
        m_waiting = false;
    }

    void FileExporterBibUtils::slotReadyStdout()
    {
        m_processBuffer->writeBlock( m_process->readStdout() );
    }

    void FileExporterBibUtils::slotReadyStderr()
    {
        TQByteArray ba = m_process->readStderr();
        TQTextStream bats( ba, IO_ReadOnly );
        bats.setEncoding( TQTextStream::UnicodeUTF8 );
        tqDebug( "%s", bats.read().latin1() );
    }

}
#include "fileexporterbibutils.moc"
