/*
 *   componentPage.cpp
 *
 *   Copyright (C) 2004 Waldo Bastian <bastian@kde.org>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License version 2 as
 *   published by the Free Software Foundation.
 *
 *   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 "componentPage.h"

#include <tqcursor.h>
#include <tqfileinfo.h>
#include <tqlabel.h>
#include <tqstylesheet.h>
#include <tqtextedit.h>
#include <tqpushbutton.h>

#include <dcopref.h>

#include <tdeapplication.h>
#include <kdebug.h>
#include <tdelistview.h>
#include <tdelocale.h>
#include <tdemessagebox.h>
#include <kprocess.h>
#include <kstdguiitem.h>

#include "component.h"
#include "kioskdata.h"
#include "kioskrun.h"

ComponentPage::ComponentPage( ComponentData *data, Component *component, TQWidget* parent, const char* name, WFlags fl )
 : ComponentPageUI(parent, name, fl), PageWidget(this), m_data(data), m_component(component)
{
  m_process = 0;
  connect(pbSetup, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotSetup()));
  connect(pbPreview, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotPreview()));

  pbSetup->setText(i18n("&Setup %1").arg(m_data->caption));
  pbPreview->setText(i18n("&Preview %1").arg(m_data->caption));
  
  if (m_data->preview.exec.isEmpty())
     pbPreview->hide();
  
  if (m_data->setup.exec.isEmpty())
     pbSetup->hide();
     
  if (!pbPreview->isHidden() && !pbSetup->isHidden())
  {
     static bool firstTime = true;
       
     if (firstTime)
     {
        firstTime = false;
        TQTimer::singleShot(0, this, TQ_SLOT(slotShowNotice()));
     }
  }

  fillActionList(listComponentConfig, m_data);
  
  connect(listComponentConfig, TQ_SIGNAL(currentChanged(TQListViewItem *)),
          this, TQ_SLOT(slotShowAction(TQListViewItem *)));
  slotShowAction(listComponentConfig->currentItem());          
}

ComponentPage::~ComponentPage()
{
   delete m_component;
}

void ComponentPage::slotShowNotice()
{
   KMessageBox::information(this, 
         i18n("Selecting the Setup or Preview option may cause the panel and/or the desktop to be temporarily shut down. "
              "To prevent data loss please make sure you are not actively using these components."),
         i18n("Attention"), "shutdown_notice");
}

void ComponentPage::load()
{
}

bool ComponentPage::save()
{
   return saveActionListChanges(listComponentConfig);
}
   
void ComponentPage::setFocus()
{
   listComponentConfig->setFocus();
}

TQString ComponentPage::subCaption()
{
  return i18n("Setup %1").arg(m_data->caption);
}

void ComponentPage::slotSetup()
{
   if (m_process)
   {
      m_process->kill();
      delete m_process;
   }
   TQCString dcopApp = m_data->setup.dcop.utf8();
   TQCString dcopObj = "qt/" + dcopApp;
   if (!dcopApp.isEmpty() && m_data->setup.hasOption("restart"))
      DCOPRef(dcopApp, dcopObj).call("quit");

   TQApplication::setOverrideCursor( TQCursor(TQt::WaitCursor) );
   if (!KioskRun::self()->prepare())
   {
      TQApplication::restoreOverrideCursor();
      KMessageBox::sorry(this, 
          i18n("<qt>There was an unexpected problem with the runtime environment.</qt>"));
      return;
   }
   KioskRun::self()->makeMutable(true);
   if (!save())
   {
      TQApplication::restoreOverrideCursor();
      return;
   }
   if (m_component)
      m_component->slotSetupPrepare();
   KioskRun::self()->updateSycoca();
   TQApplication::restoreOverrideCursor();

   if (!dcopApp.isEmpty())
   {
      KioskRun::self()->dcopClient()->setNotifications(true);
      connect(KioskRun::self()->dcopClient(), TQ_SIGNAL(applicationRegistered( const TQCString& )),
           this, TQ_SLOT(slotSetupAppRegistered( const TQCString& )));
   }

   TQStringList args;
   if (m_data->setup.hasOption("nofork"))
      args << "--nofork";

   args += m_data->setup.args;

   m_process = KioskRun::self()->run(m_data->setup.exec, args);
   int result = KMessageBox::questionYesNo(this, 
         i18n("<qt>You can now configure %1. "
              "When you are finished click <b>Save</b> to make the new configuration permanent.")
              .arg(m_data->caption), i18n("%1 Setup").arg(m_data->caption),
              KStdGuiItem::save(), KStdGuiItem::discard());
   m_saveSettings = (result == KMessageBox::Yes);
   if (!dcopApp.isEmpty())
      KioskRun::self()->dcopRef(dcopApp, dcopObj).call("quit");

   if (m_process->isRunning())
   {
      connect(m_process, TQ_SIGNAL(processExited(TDEProcess *)), this, TQ_SLOT(slotPreviewDone()));
   }
   else
   {
      slotSetupDone();
   }
}

void ComponentPage::slotSetupDone()
{
   delete m_process;
   m_process = 0;

   KioskRun::self()->dcopClient()->setNotifications(false);
   disconnect(KioskRun::self()->dcopClient(), TQ_SIGNAL(applicationRegistered( const TQCString& )),
              this, TQ_SLOT(slotSetupAppRegistered( const TQCString& )));

   KioskRun::self()->makeMutable(false);
   if (m_saveSettings)
   {
      bool result = true;
      if (m_component)
         result = m_component->setupFinished();
      
      if (!result) return;

      // Find new config files.
      TQStringList newFiles = KioskRun::self()->newConfigFiles();
      for(TQStringList::ConstIterator it = newFiles.begin();
          it != newFiles.end(); ++it)
      {
         if (m_data->ignoreFiles.contains(*it))
         {
            kdDebug() << "Ignoring new config file " << (*it) << endl;
            continue;
         }
         KioskRun::self()->mergeConfigFile(*it);
      }
   }
   KioskRun::self()->flushConfigCache();

   if (m_data->setup.hasOption("restart"))
      TDEApplication::tdeinitExec(m_data->setup.exec);
}

void ComponentPage::slotSetupAppRegistered( const TQCString &appid)
{
   TQCString dcopApp = m_data->setup.dcop.utf8();
   if (dcopApp == appid)
   {
      kdDebug() << appid << " is up and running" << endl;
      if (m_component)
         m_component->slotSetupStarted();
   }
}

void ComponentPage::slotPreview()
{
   if (m_process)
   {
      m_process->kill();
      delete m_process;
   }
   TQCString dcopApp = m_data->preview.dcop.utf8();
   TQCString dcopObj = "qt/" + dcopApp;
   if (!dcopApp.isEmpty() && m_data->preview.hasOption("restart"))
      DCOPRef(dcopApp, dcopObj).call("quit");

   TQApplication::setOverrideCursor( TQCursor(TQt::WaitCursor) );
   KioskRun::self()->prepare();
   save();
   KioskRun::self()->updateSycoca();
   TQApplication::restoreOverrideCursor();

   if (!dcopApp.isEmpty())
   {
      KioskRun::self()->dcopClient()->setNotifications(true);
      connect(KioskRun::self()->dcopClient(), TQ_SIGNAL(applicationRegistered( const TQCString& )),
           this, TQ_SLOT(slotPreviewAppRegistered( const TQCString& )));
   }

   TQStringList args;
   if (m_data->preview.hasOption("nofork"))
      args << "--nofork";

   args += m_data->preview.args;

   m_process = KioskRun::self()->run(m_data->preview.exec, args);
   KMessageBox::information(this, 
         i18n("<qt>This is how %1 will behave and look with the new settings. "
              "Any changes you now make to the settings will not be saved.<p>"
              "Click <b>Ok</b> to return to your own personal %2 configuration.")
              .arg(m_data->caption, m_data->caption), i18n("%1 Preview").arg(m_data->caption));
   if (!dcopApp.isEmpty())
      KioskRun::self()->dcopRef(dcopApp, dcopObj).call("quit");

   if (m_process->isRunning())
   {
      connect(m_process, TQ_SIGNAL(processExited(TDEProcess *)), this, TQ_SLOT(slotPreviewDone()));
   }
   else
   {
      slotPreviewDone();
   }
}

void ComponentPage::slotPreviewAppRegistered( const TQCString &appid)
{
   TQCString dcopApp = m_data->preview.dcop.utf8();
   if (dcopApp == appid)
   {
      kdDebug() << appid << " is up and running" << endl;
      if (m_component)
         m_component->slotPreviewStarted();
   }
}

void ComponentPage::slotPreviewDone()
{
   KioskRun::self()->dcopClient()->setNotifications(false);
   disconnect(KioskRun::self()->dcopClient(), TQ_SIGNAL(applicationRegistered( const TQCString& )),
              this, TQ_SLOT(slotPreviewAppRegistered( const TQCString& )));

   delete m_process;
   m_process = 0;
   if (m_data->preview.hasOption("restart"))
      TDEApplication::tdeinitExec(m_data->preview.exec);
}

void ComponentPage::slotShowAction(TQListViewItem *item)
{
   ComponentActionItem *actionItem = dynamic_cast<ComponentActionItem*>(item);
   TQString description;
   if (actionItem)
   {
      description = "<h2>"+TQStyleSheet::escape(actionItem->action()->caption)+"</h2>\n";
      description += actionItem->action()->description;
   }
   componentDescription->setText(description);
}

#include "componentPage.moc"
