/*
    Copyright (c) 2003 Alexander Kellett <lypanov@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License (LGPL) as published by the Free Software Foundation;
    either version 2 of the License, or (at your option) any later
    version.

    This library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include <tqfile.h>

#include <kdebug.h>
#include <tdeaction.h>
#include <tdeglobal.h>
#include <tdeconfig.h>
#include <tdeinstance.h>
#include <tdehtml_part.h>
#include <kgenericfactory.h>

#include <kstandarddirs.h>

#include <krun.h>
#include <kservice.h>

#include <tdepopupmenu.h>
#include <kbookmarkimporter.h>
#include <kbookmarkmanager.h>

#include "minitoolsplugin.h"

typedef KGenericFactory<MinitoolsPlugin> MinitoolsPluginFactory;
K_EXPORT_COMPONENT_FACTORY( libminitoolsplugin, MinitoolsPluginFactory("minitoolsplugin") )

MinitoolsPlugin::MinitoolsPlugin(TQObject* parent, const char* name, const TQStringList &)
   : KParts::Plugin(parent, name) {
  m_part = (parent && parent->inherits( "TDEHTMLPart" )) ? static_cast<TDEHTMLPart*>(parent) : 0L;

  m_pMinitoolsMenu = new TDEActionMenu(i18n("&Minitools"), "minitools", actionCollection(), "minitools");

  m_pMinitoolsMenu->setDelayed(false);
  m_pMinitoolsMenu->setEnabled(true);

  connect(m_pMinitoolsMenu->popupMenu(), TQ_SIGNAL( aboutToShow() ),
                                   this, TQ_SLOT( slotAboutToShow() ));
}

MinitoolsPlugin::~MinitoolsPlugin() {
   ;
}

void MinitoolsPlugin::slotAboutToShow() {

  m_minitoolsList.clear();
  KXBELBookmarkImporterImpl importer;
  connect(&importer, TQ_SIGNAL( newBookmark( const TQString &, const TQCString &, const TQString &) ),
                     TQ_SLOT( newBookmarkCallback( const TQString &, const TQCString &, const TQString & ) ));
  connect(&importer, TQ_SIGNAL( endFolder() ), 
                     TQ_SLOT( endFolderCallback() ));
  TQString filename = minitoolsFilename(true);
  if (!filename.isEmpty() && TQFile::exists(filename)) {
     importer.setFilename(filename);
     importer.parse();
  }
  filename = minitoolsFilename(false);
  if (!filename.isEmpty() && TQFile::exists(filename)) {
     importer.setFilename(filename);
     importer.parse();
  }

  m_pMinitoolsMenu->popupMenu()->clear();

  int count = m_pMinitoolsMenu->popupMenu()->count(); // why not 0???
  bool gotSep = true; // don't start with a sep

  if (m_minitoolsList.count() > 0) {
     MinitoolsList::ConstIterator e = m_minitoolsList.begin();
     for( ; e != m_minitoolsList.end(); ++e ) {
        if ( ((*e).first  == "-") 
          && ((*e).second == "-")
        ) {
           if (!gotSep)
              m_pMinitoolsMenu->popupMenu()->insertSeparator();
           gotSep = true;
           count++;
        } else {
           TQString str = (*e).first;
           // emsquieezzy thingy?
           if (str.length() > 48) {
              str.truncate(48);
              str.append("...");
           }
           m_pMinitoolsMenu->popupMenu()->insertItem( 
              str, this,
              TQ_SLOT(slotItemSelected(int)),
              0, ++count );
           gotSep = false;
        }
     }
  }

  if (!gotSep) {
     // don't have an extra sep
     m_pMinitoolsMenu->popupMenu()->insertSeparator();
  }

  m_pMinitoolsMenu->popupMenu()
                       ->insertItem(i18n("&Edit Minitools"), 
                                    this, TQ_SLOT(slotEditBookmarks()),
                                    0, ++count );  
}

void MinitoolsPlugin::newBookmarkCallback(
   const TQString & text, const TQCString & url, const TQString & 
) {
  kdDebug(90150) << "MinitoolsPlugin::newBookmarkCallback" << text << url << endl;
  m_minitoolsList.prepend(qMakePair(text,url));
}

void MinitoolsPlugin::endFolderCallback() {
  kdDebug(90150) << "MinitoolsPlugin::endFolderCallback" << endl;
  m_minitoolsList.prepend(qMakePair(TQString("-"),TQCString("-")));
}

TQString MinitoolsPlugin::minitoolsFilename(bool local) {
  return local ? locateLocal("data", TQString::fromLatin1("konqueror/minitools.xml"))
               : locateLocal("data", TQString::fromLatin1("konqueror/minitools-global.xml"));
}

void MinitoolsPlugin::slotEditBookmarks() {
   KBookmarkManager *manager = KBookmarkManager::managerForFile(minitoolsFilename(true));
   manager->slotEditBookmarks();
}

void MinitoolsPlugin::slotItemSelected(int id) {
  if (m_minitoolsList.count() == 0)
     return;
  TQString tmp = m_minitoolsList[id-1].second;
  TQString script = KURL::decode_string(tmp.right(tmp.length() - 11)); // sizeof("javascript:")
  connect(this, TQ_SIGNAL( executeScript(const TQString &) ),
          m_part, TQ_SLOT( executeScript(const TQString &) ));
  emit executeScript(script);
  disconnect(this, TQ_SIGNAL( executeScript(const TQString &) ), 0, 0);
}

#include "minitoolsplugin.moc"
