/***************************************************************************
 *   Copyright (C) 2004 by Marco Kraus                                     *
 *   marco@linuxstuff.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 "pdfkreator.h"

pdfkreator::pdfkreator(QWidget* parent, const char* name, bool modal, WFlags fl)
: PDFKreatorDialog(parent,name, modal,fl)
{
  // set output directory to user dir
  OutputDir->insert(QDir::homeDirPath());  // default output directory for concat
  
  running = false; // nothing running at the moment; general running flag
  concatStart = false;
}

pdfkreator::~pdfkreator()
{
}

void pdfkreator::Create(){
  if( JoinFilesBox->count() > 0 ){  // if any images were added
    Convert(); // first convert all files
  }else{
    TextOutput->append(i18n("<font color=red><h4>Please add data files first!</h4></font><p>"));
  }  
 return;  
}

void pdfkreator::Convert(){
     TextOutput->clear(); // clear textbox with every conversion  
     buttonCreate->setText(i18n("Abort"));   // set abort button
   
     if( OutputName->text() == ""){ // if no output name was specified...
        OutputName->setText("output"); // ...we set a default value
     }
                   
     TextOutput->append(i18n("<font color=green><h4>Starting PDF creation:</h4></font><p>"));
     TextOutput->append(i18n("<font color=green><h4>converting files to TIF:</h4></font>"));
        
     ProcessCounter = 0;  
     for( uint i = 0; i < JoinFilesBox->count(); i++){   
        ProcessCounter++; // inc for new process
        
        tifgen = new QProcess();         // now set up a new conversion process                
        tifgen->addArgument( "convert" );  // use image magick's converter
        tifgen->addArgument( JoinFilesBox->item(i)->text() );  // input file
        tifgen->addArgument( JoinFilesBox->item(i)->text()+".tif" );  // output file
                                
        // connect the stdout/stderr output of convert to the textbox
        connect( tifgen, SIGNAL(readyReadStdout()),this, SLOT(readFromTIFStdout()) );
        //connect( tifgen, SIGNAL(readyReadStderr()),this, SLOT(readFromTIFStderr()) );  // disabled to supress bothering debug messages
        connect( tifgen, SIGNAL(processExited()),this, SLOT(tifgenExiting()) ); 

        // debug: output all arguments
        TextOutput->append("<font color=black>"+tifgen->arguments().join(" ")+"<br>Please wait...</font>");  // debug: show all option arguments     
     
        // start the process  
        tifgen->start();                
        
     }        
  return;      
}   

void pdfkreator::ConCat(){     
          
  TextOutput->append(i18n("<font color=green><h4>Creating output Postscript</h4></font>"));             
  
  QString mergeCommand = "tiff2ps -2 -c -i 0 -p -x -y -z ";
  
  for( uint i = 0; i < JoinFilesBox->count(); i++){  // create command string       
     iname = JoinFilesBox->item(i)->text()+".tif";
     mergeCommand = mergeCommand+iname+" ";
  }  

  if( OutputDir->text().endsWith("/") ) // check for ending slash
     oname = OutputDir->text()+OutputName->text()+".ps"; 
  else
     oname = OutputDir->text()+"/"+OutputName->text()+".ps";   
  
  mergeCommand = mergeCommand+" -O "+oname;
    
  psgen = new QProcess();         // now set up a new conversion process                
  QStringList psgenArgList = NULL;
  psgenArgList = psgenArgList.split( " ", mergeCommand ); // create StringList for arguments
  psgen->setArguments( psgenArgList );
                                
  // connect the stdout/stderr output of convert to the textbox
  connect( psgen, SIGNAL(readyReadStdout()),this, SLOT(readFromPSStdout()) );
  connect( psgen, SIGNAL(readyReadStderr()),this, SLOT(readFromPSStderr()) );  // disabled to supress bothering debug messages
  connect( psgen, SIGNAL(processExited()),this, SLOT(psgenExiting()) ); 
  
  // debug: output all arguments
  TextOutput->append("<font color=black>"+psgen->arguments().join(" ")+"<br>Please wait...</font>");  // debug: show all option arguments       
  TextOutput->append(i18n("<font color=green><h4>starting tiff2ps now</h4></font>"));                    
  psgen->start();  // start the process  

  return;
}

void pdfkreator::TransPDF(){  
  
  if( OutputDir->text().endsWith("/") ) // check for ending slash
     pdfname = OutputDir->text()+OutputName->text()+".pdf"; 
  else
     pdfname = OutputDir->text()+"/"+OutputName->text()+".pdf";          

  pdfgen = new QProcess();         // now set up a new conversion process                
  pdfgen->addArgument( "ps2pdf" );  // use image magick's converter
  pdfgen->addArgument( oname );  // input file
  pdfgen->addArgument( pdfname );  // output file
                                
  // connect the stdout/stderr output of convert to the textbox
  connect( pdfgen, SIGNAL(readyReadStdout()),this, SLOT(readFromPDFStdout()) );
  connect( pdfgen, SIGNAL(readyReadStderr()),this, SLOT(readFromPDFStderr()) );  // disabled to supress bothering debug messages
  connect( pdfgen, SIGNAL(processExited()),this, SLOT(pdfgenExiting()) ); 

  // debug: output all arguments
  TextOutput->append("<font color=black>"+pdfgen->arguments().join(" ")+"<br>Please wait...</font>");  // debug: show all option arguments     

  // start the process  
  pdfgen->start();                
        
 return;
}

void pdfkreator::CleanUp(){
  
  TextOutput->append(i18n("<p><font color=green><h4>Cleaning up temporary file...</h4></font>"));           
  // delete temp. tiff files
  for( uint i = 0; i < JoinFilesBox->count(); i++){  // create command string       
     QString DelFile = JoinFilesBox->item(i)->text()+".tif";
     unlink(DelFile);
  }  

  // also unlink temp. PS output file
  unlink(oname);     
  
  TextOutput->append(i18n("<p><font color=green><h4>Finished: PDF created</h4></font>"));        
  running = false; // process is running
  concatStart=false;
  buttonCreate->setText(i18n("Create PDF"));   // set abort button
}

void pdfkreator::tifgenExiting(){
        ProcessCounter--; // dec for new process
        if( ProcessCounter <= 0 ){  // if this was the last process
              TextOutput->append(i18n("<p><font color=green><h4>Starting concat</h4></font>"));                              
              ConCat();  // concat them into one big ostscript file                           
        }
        return;      
}

void pdfkreator::psgenExiting(){
   TextOutput->append(i18n("<font color=green><h4>Postscript file created</h4></font>"));             
   TransPDF(); // now transfer ps to pdf
   return;
}

void pdfkreator::pdfgenExiting(){
  TextOutput->append(i18n("<font color=green><h4>PDF file created</h4></font>"));             
  CleanUp(); // now clean up everything
  return;      
}

void pdfkreator::SelectJoinFiles()
{
  static QString homedir = QDir::homeDirPath();                              
  QStringList JoinFiles = QFileDialog::getOpenFileNames(i18n("Images (*.jpg *.png *.bmp *.tif *.gif);;all (*.*)"), homedir, this, i18n("open files dialog"), i18n("Choose files") );
                                
  QStringList::Iterator it = JoinFiles.begin();
  while( it != JoinFiles.end() ) {
      QListBoxText* newBox = new QListBoxText(*it);
      JoinFilesBox->insertItem(newBox);
      ++it;
  }  
}

void pdfkreator::MoveUp()
{
 if( JoinFilesBox->currentItem() >= 0){ // none selected
   QListBoxText* Lbt = new QListBoxText( JoinFilesBox->item(JoinFilesBox->currentItem())->text() );   
   JoinFilesBox->insertItem( Lbt, JoinFilesBox->currentItem()-1 ); 
   JoinFilesBox->removeItem( JoinFilesBox->currentItem() );
   JoinFilesBox->setCurrentItem( Lbt );
 }
}

void pdfkreator::MoveDown()
{
 if( JoinFilesBox->currentItem() >= 0){ // none selected
  if( (uint)JoinFilesBox->currentItem() == (JoinFilesBox->count())-1 ){ // last entry selected
   QListBoxText* Lbt = new QListBoxText( JoinFilesBox->item(JoinFilesBox->currentItem())->text() );   
   JoinFilesBox->insertItem( Lbt, 0 ); 
   JoinFilesBox->removeItem( JoinFilesBox->currentItem() );
   JoinFilesBox->setCurrentItem( 0 );
  }else{
   QListBoxText* Lbt = new QListBoxText( JoinFilesBox->item(JoinFilesBox->currentItem())->text() );   
   JoinFilesBox->insertItem( Lbt, JoinFilesBox->currentItem()+2 ); 
   JoinFilesBox->removeItem( JoinFilesBox->currentItem() );
   JoinFilesBox->setCurrentItem( Lbt );
  }
 } 
}

void pdfkreator::RotateRight(){  
 if( JoinFilesBox->currentItem() >= 0){ // none selected        
   rotate = new QProcess();         // now set up a new conversion process                
   rotate->addArgument( "convert" );  // use image magick's converter
   rotate->addArgument( "-rotate" );  // use image magick's converter
   rotate->addArgument( "90" );  // use image magick's converter      
   rotate->addArgument( JoinFilesBox->item(JoinFilesBox->currentItem())->text() );  // output file
   rotate->addArgument( JoinFilesBox->item(JoinFilesBox->currentItem())->text() );  // output file
        
   // connect the stdout/stderr output of convert to the textbox
   connect( rotate, SIGNAL(readyReadStdout()),this, SLOT(readFromRotateStdout()) );
   connect( rotate, SIGNAL(readyReadStderr()),this, SLOT(readFromRotateStderr()) );  // disabled to supress bothering debug messages
   connect( rotate, SIGNAL(processExited()),this, SLOT(rotateExiting()) ); 

   // debug: output all arguments
   TextOutput->append("<font color=black>"+rotate->arguments().join(" ")+"<br>Please wait...</font>");  // debug: show all option arguments     
     
   // start the process  
   rotate->start();                
 }
}

void pdfkreator::RotateLeft(){  
if( JoinFilesBox->currentItem() >= 0){ // none selected        
   rotate = new QProcess();         // now set up a new conversion process                
   rotate->addArgument( "convert" );  // use image magick's converter
   rotate->addArgument( "-rotate" );  // use image magick's converter
   rotate->addArgument( "270" );  // use image magick's converter      
   rotate->addArgument( JoinFilesBox->item(JoinFilesBox->currentItem())->text() );  // output file
   rotate->addArgument( JoinFilesBox->item(JoinFilesBox->currentItem())->text() );  // output file
        
   // connect the stdout/stderr output of convert to the textbox
   connect( rotate, SIGNAL(readyReadStdout()),this, SLOT(readFromRotateStdout()) );
   connect( rotate, SIGNAL(readyReadStderr()),this, SLOT(readFromRotateStderr()) );  // disabled to supress bothering debug messages
   connect( rotate, SIGNAL(processExited()),this, SLOT(rotateExiting()) ); 

   // debug: output all arguments
   TextOutput->append("<font color=black>"+rotate->arguments().join(" ")+"<br>Please wait...</font>");  // debug: show all option arguments     
     
   // start the process  
   rotate->start();                
 }
}

void pdfkreator::previewFile(){
if( JoinFilesBox->currentItem() >= 0){ // none selected        
   
   preview = new QProcess();         // now set up a new conversion process                
   preview->addArgument( "display" );  // use image magick's converter
   preview->addArgument( JoinFilesBox->item(JoinFilesBox->currentItem())->text() );  // output file
   
   //connect( rotate, SIGNAL(processExited()),this, SLOT(rotateExiting()) );            
   // debug: output all arguments
   TextOutput->append("<font color=black>"+preview->arguments().join(" ")+"</font>");  // debug: show all option arguments     
     
   // start the process  
   preview->start();                

 }
}

void pdfkreator::rotateExiting(){
  //delete rotate;
  TextOutput->append(i18n("<font color=green><h4>File rotated correctly</h4></font>")); 
  return;      
}

void pdfkreator::RemoveJoinFile()
{
  JoinFilesBox->removeItem( JoinFilesBox->currentItem() );
}

void pdfkreator::SelectOutputDir()
{
  static QString olddirname = QDir::homeDirPath();
  QString dirname = QFileDialog::getExistingDirectory( olddirname, this, i18n("open file dialog"), i18n("Choose a directory") );
  if (dirname != NULL) {
       OutputDir->clear();
       OutputDir->insert(dirname);
       olddirname = dirname;
  }  
}

void pdfkreator::readFromPSStderr(){
      TextOutput->append( psgen->readStderr() );
}

void pdfkreator::readFromPSStdout(){
      TextOutput->append( psgen->readStderr() );
}

void pdfkreator::readFromTIFStderr(){
      TextOutput->append( tifgen->readStderr() );
}

void pdfkreator::readFromTIFStdout(){
      TextOutput->append( tifgen->readStderr() );
}

void pdfkreator::readFromPDFStderr(){
      TextOutput->append( pdfgen->readStderr() );
}

void pdfkreator::readFromPDFStdout(){
      TextOutput->append( pdfgen->readStderr() );
}

void pdfkreator::readFromRotateStderr(){
      TextOutput->append( rotate->readStderr() );
}

void pdfkreator::readFromRotateStdout(){
      TextOutput->append( rotate->readStderr() );
}

void pdfkreator::quitPDFKreator(){
   this->close();
}   

#include "pdfkreator.moc"
