/* -*- indent-tabs-mode: nil; -*-
 *
 * This file is part of the Mango recipe management distribution.
 * Copyright (c) 2000-2003, Roland Jesse
 * All rights reserved.
 *
 * For license and copyright information see the file COPYRIGHT or 
 * <http://www.opensource.org/licenses/bsd-license.html>.
 *
 * $Id: DocManager.cpp,v 1.5 2003/10/27 14:14:43 rjesse Exp $
 */

#include "DocManager.h"
#include <qassistantclient.h>
#include <qmessagebox.h>
#include <qprocess.h>

DocManager* DocManager::m_instance = 0;

/*! Singleton access. */
DocManager*
DocManager::getInstance()
{
   if (m_instance == 0) {
      m_instance = new DocManager();
      m_instance->initAssistant();
   }
   return m_instance;
}

/*! Delete the singleton instance. */
void
DocManager::deleteInstance()
{
   if (m_instance != 0) {
      delete m_instance;
      m_instance = 0;
   }
}

/*! Constructor. Don't use directly but getInstance() instead. */
DocManager::DocManager()
   : QObject(), m_docRootSet( false), m_assistantOk( false), m_assistantIsRunning( false)
{
}

/*!
  Initialise the assistant process.
*/
void DocManager::
initAssistant()
{
   // Starting with Qt version 3.1.0, assistant can handle added docs.
   if (QT_VERSION >= 0x030100 && m_docRootSet) {
      m_assistantClient = new QAssistantClient( "", this, "m_assistantClient");
      QString contentpath = m_docRoot.filePath( "content.dcf");
      QProcess* process = new QProcess( this);
      process->addArgument( "assistant");
      process->addArgument( "-addContentFile");
      process->addArgument( contentpath);

      if (process->start())
         m_assistantOk = true;
   }
}

DocManager::~DocManager()
{
   if (m_assistantOk) {
      QString contentpath = m_docRoot.filePath( "content.dcf");
      QProcess* process = new QProcess( this);
      process->addArgument( "assistant");
      process->addArgument( "-removeContentFile");
      process->addArgument( contentpath);      
   }
}

QString
DocManager::getRootDirName() const
{
   return m_docRoot.path();
}

void
DocManager::slotSetRootDir( const QString& path)
{
   QDir dir( path);
   m_docRoot = dir;
   if (! m_docRootSet) {
      m_docRootSet = true;
      initAssistant();
   }
}

/*!
  \todo verify whether or not it is possible to fire up
        assistant only if !m_assistantIsRunning.
*/
void
DocManager::slotOpen( const QString& path)
{
   QString fullpath = m_docRoot.filePath( path);
   QProcess* process = new QProcess( this);
   process->addArgument( "assistant");
   process->addArgument( fullpath);

   if (!process->start()) {
      QMessageBox::warning( 0, tr( "Online documentation not available."),
                            tr( "Could not open the documentation tool."));
      m_assistantIsRunning = false;
   }
   else {
      m_assistantIsRunning = true;
      connect( process, SIGNAL( processExited()),
               this, SLOT( slotAssistantExited()));
   }
} // slotOpen()

void
DocManager::slotAssistantExited()
{
   m_assistantIsRunning = false;
}
