/*
 *   menueditComponent.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 "menueditComponent.h"

#include <qdir.h>
#include <qdom.h>
#include <qfileinfo.h>

#include <kapplication.h>
#include <kdebug.h>
#include <kmimetype.h>
#include <kprocess.h>
#include <ksavefile.h>
#include <ksimpleconfig.h>
#include <kstandarddirs.h>
#include <kurl.h>

#include "kioskrun.h"
#include "kiosksync.h"

MenuEditComponent::MenuEditComponent( QObject *parent)
 : Component(parent)
{
}

MenuEditComponent::~MenuEditComponent()
{
}

void
MenuEditComponent::slotSetupPrepare()
{
   (void) KioskRun::self()->locateLocal("xdgconf-menu", "applications-kmenuedit.menu"); // Create dir
}

void
MenuEditComponent::slotSetupStarted()
{
}

static QDomDocument loadDoc(const QString &fileName)
{
   QDomDocument doc;

   QFile file( fileName );
   if ( !file.open( IO_ReadOnly ) )
   {
      kdWarning() << "Could not open " << fileName << endl;
      return doc;
   }
   QString errorMsg;
   int errorRow;
   int errorCol;
   if ( !doc.setContent( &file, &errorMsg, &errorRow, &errorCol ) ) {
      kdWarning() << "Parse error in " << fileName << ", line " << errorRow << ", col " << errorCol << ": " << errorMsg << endl;
      file.close();
      return doc;
   }
   file.close();
   return doc;
}

static bool saveDoc(const QString &fileName, QDomDocument doc)
{
   KSaveFile saveFile(fileName);

   QTextStream *stream = saveFile.textStream();
   if (!stream)
   {
      kdWarning() << "Could not write " << fileName << endl;
      return false;
   }
   (*stream) << doc.toString();

   if (!saveFile.close())
   {
      kdWarning() << "Could not write " << fileName << endl;
      return false;
   }

   return true;
}


bool
MenuEditComponent::setupFinished()
{
   bool result;
   QString menuEditFile = KioskRun::self()->locateLocal("xdgconf-menu", "applications-kmenuedit.menu");
   QString menuFile = KioskRun::self()->locate("xdgconf-menu", "applications.menu");
   QString menuFileSave = KioskRun::self()->locateSave("xdgconf-menu", "applications.menu");

   kdDebug() << "MenuEditComponent: menuEditFile = " << menuEditFile << endl;
   kdDebug() << "MenuEditComponent: menuFile = " << menuFile << endl;
   kdDebug() << "MenuEditComponent: menuFileSave = " << menuFileSave << endl;

   QDomDocument docChanges = loadDoc(menuEditFile);
   if (docChanges.isNull())
   {
       kdDebug() << "No menu changes." << endl;
       return true;
   }

   QDomDocument doc = loadDoc(menuFile);
   if (doc.isNull())
   {
       kdWarning() << "Can't find menu file!" << endl;
       return true;
   }

   QDomElement docElem = doc.documentElement();
   QDomNode n = docElem.firstChild();
   QDomNode next;
   for(; !n.isNull(); n = next ) 
   {
      QDomElement e = n.toElement(); // try to convert the node to an element.
      next = n.nextSibling();

      if ((e.tagName() == "MergeFile") && (e.text() == "applications-kmenuedit.menu"))
         break;
   }
   QDomNode insertionPoint = n;
   if (insertionPoint.isNull())
   {
      kdWarning() << "Application menu fails to include applications-kmenuedit.menu" << endl;
      return false;
   }
   QDomElement docChangesElem = docChanges.documentElement();
   n = docChangesElem.firstChild();
   for(; !n.isNull(); n = next ) 
   {
      QDomElement e = n.toElement(); // try to convert the node to an element.
      next = n.nextSibling();

      docElem.insertBefore(n, insertionPoint);
   }

   KTempFile tempFile;
   tempFile.close();

   saveDoc(tempFile.name(), doc);
   result = KioskRun::self()->install(tempFile.name(), menuFileSave);
   if (!result) return false;
   

   // Install .desktop files
   {
      QString legacyApplications = KioskRun::self()->locateLocal("apps", QString::null);
      QString legacySaveApplications = KioskRun::self()->locateSave("apps", QString::null);
      
      KioskSync legacyDir(kapp->mainWidget());
      legacyDir.addDir(legacyApplications, KURL());

      QStringList newLegacyApplications = legacyDir.listFiles();
   
      for(QStringList::ConstIterator it = newLegacyApplications.begin();
          it != newLegacyApplications.end(); ++it)
      {
         if ((*it).endsWith(".desktop") || (*it).endsWith(".kdelnk") || (*it).endsWith(".directory"))
         {
            kdDebug() << "MenueditComponent: New legacy file %s" << (legacyApplications+(*it)) << endl;
            result = KioskRun::self()->install(legacyApplications+(*it), legacySaveApplications+(*it));
            if (!result) return false;
         }
      }
   }

   // Install .desktop files
   {
      QString xdgApplications = KioskRun::self()->locateLocal("xdgdata-apps", QString::null);
      QString xdgSaveApplications = KioskRun::self()->locateSave("xdgdata-apps", QString::null);

      QDir dir(xdgApplications);
      QStringList newXdgApplications = dir.entryList(QDir::All, QDir::Unsorted);
      newXdgApplications.remove(".");
      newXdgApplications.remove("..");
   
      for(QStringList::ConstIterator it = newXdgApplications.begin();
          it != newXdgApplications.end(); ++it)
      {
         if ((*it).endsWith(".desktop") || (*it).endsWith(".kdelnk"))
         {
            kdDebug() << "MenueditComponent: New .desktop file %s" << (xdgApplications+(*it)) << endl;
            result = KioskRun::self()->install(xdgApplications+(*it), xdgSaveApplications+(*it));
            if (!result) return false;
         }
      }
   }

   // Install .directory files
   {
      QString xdgDirectories = KioskRun::self()->locateLocal("xdgdata-dirs", QString::null);
      QString xdgSaveDirectories = KioskRun::self()->locateSave("xdgdata-dirs", QString::null);

      QDir dir(xdgDirectories);
      QStringList newXdgDirectories = dir.entryList(QDir::All, QDir::Unsorted);
      newXdgDirectories.remove(".");
      newXdgDirectories.remove("..");

      for(QStringList::ConstIterator it = newXdgDirectories.begin();
          it != newXdgDirectories.end(); ++it)
      {
         if ((*it).endsWith(".directory"))
         {
            kdDebug() << "MenueditComponent: New .directory file %s" << (xdgDirectories+(*it)) << endl;
            result = KioskRun::self()->install(xdgDirectories+(*it), xdgSaveDirectories+(*it));
            if (!result) return false;
         }
      }
   }

   KioskRun::self()->forceSycocaUpdate();

   return true;
}

void
MenuEditComponent::slotPreviewStarted()
{
   KioskRun::self()->dcopRef("kicker", "kicker").call("showKMenu");
}


#include "menueditComponent.moc"
