#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <qstring.h>

#include <kconfig.h>
#include <kinstance.h>
#include <klocale.h>
#include <knotifyclient.h>

#include "kgv_view.h"

extern "C" {
#include "ps.h"
}

#ifndef _PATH_TMP
#define _PATH_TMP "/tmp/"
#endif

#include "kdsc.h"

using namespace KDSC;

Document::Document( const QString& fileName )
    : _fileName( fileName )
{
    _isScanned = false;
    _doc = 0;
}

bool Document::scan( FILE** PSFile )
{
    KConfig* config = KGVFactory::instance()->config();
    QString interpreterPath = config->readEntry( "Interpreter", "gs" );

    _pages.setAutoDelete( true );

    struct document* doc;
 
    char* filename_dscP = 0;
    char* filename_uncP = 0;
    QString cmd_scan_pdf = interpreterPath + " -dNODISPLAY -dQUIET -sPDFname=%s -sDSCname=%s pdf2dsc.ps -c quit";
    const char* cmd_uncompress = "gzip -d -c %s > %s";
    
    doc = psscan( PSFile, QFile::encodeName( _fileName ), 
		  _PATH_TMP"/kghostview", &filename_dscP,
		  cmd_scan_pdf.local8Bit(), &filename_uncP, cmd_uncompress );

    if( filename_dscP ) {
	unlink( filename_dscP );
	free( filename_dscP );
    }
  
    if( filename_uncP ) {
	unlink( filename_uncP );
	free( filename_uncP );
    }
   
    if( !doc ) {
	KNotifyClient::userEvent( i18n( "Can't load the file. Its contents may be encrypted or corrupted." ), KNotifyClient::Messagebox);
	return false;
    }
   
    _isEPSF = static_cast<bool>( doc->epsf );

    _title = QString( doc->title );
    _date = QString( doc->date );
   
    _headerOffset   = Offset( doc->beginheader, doc->endheader, 
			      doc->lenheader ); 
    _previewOffset  = Offset( doc->beginpreview, doc->endpreview, 
			      doc->lenpreview ); 
    _defaultsOffset = Offset( doc->begindefaults, doc->enddefaults, 
			      doc->lendefaults ); 
    _prologOffset   = Offset( doc->beginprolog, doc->endprolog, 
			      doc->lenprolog ); 
    _setupOffset    = Offset( doc->beginsetup, doc->endsetup, 
			      doc->lensetup ); 
    _trailerOffset  = Offset( doc->begintrailer, doc->endtrailer, 
			      doc->lentrailer ); 
   
    _boundingBox = BoundingBox( doc->boundingbox );
    _defaultPageBoundingBox = BoundingBox( doc->default_page_boundingbox );
    
    _orientation = doc->orientation;
    _defaultPageOrientation = doc->default_page_orientation;
    
    _numberOfPages = doc->numpages;
    
    _pages.resize( doc->numpages );

    for( unsigned int i = 0; i < doc->numpages; ++i ) {
	Page* page = new Page;
	page->_number = i + 1;
	page->_label = QString( doc->pages[i].label );
	page->_boundingBox = BoundingBox( doc->pages[i].boundingbox );
	page->_orientation = doc->pages[i].orientation;
	page->_offset = Offset( doc->pages[i].begin, doc->pages[i].end, 
				doc->pages[i].len );
	_pages.insert( i, page );
    }

    _doc = doc;

    return true;
}

Document::~Document()
{
    if( _doc )
	psfree( _doc );
    _doc = 0;
}

