/***************************************************************************
 *   Copyright (C) 2005 Novell, Inc.                                       *
 *                                                                         *
 *   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.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA           *
 ***************************************************************************/

#include <QString>
#include <QStringList>
#include <QDir>
#include <QClipboard>
#include <kfiledialog.h>
#include <kcmdlineargs.h>
#include <fcntl.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <khelpmenu.h>
#include <kprocess.h>

#include <QToolTip>
#include <qdom.h>
#include <QTimer>

#include "searchdlg.h"
#include "kerryapp.h"
#include <kaction.h>
#include <kactioncollection.h>
#include <kshortcut.h>
#include <kmenu.h>
#include <kiconloader.h>
#include <klineedit.h>
#include <kpassivepopup.h>
#include <kcombobox.h>

#define HISTORY_ITEMS_START_ID 100
#define HISTORY_ITEMS_CLEAR_ID 99


KerryApplication::KerryApplication() : KUniqueApplication(),
    hitListWindow(0), sysTrayIcon(0)
{
}

KerryApplication::~KerryApplication()
{
  if (hitListWindow) {
    KConfigGroup config = KGlobal::config()->group("Default");
    config.writeEntry("History", hitListWindow->editSearch->historyItems());
    config.writeEntry("DialogSize", hitListWindow->size());
    config.sync();

    delete hitListWindow;
  }
}

int KerryApplication::newInstance()
{
    if (!hitListWindow)
        init();

        KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
        if (args->isSet("show-searchdialog")) {
            hitListWindow->showSearchDialog();
        }

        if (args->count()==1)
           search(args->arg(0));

        args->clear();

    return KUniqueApplication::newInstance();
}

void KerryApplication::init()
{
  if (hitListWindow)
      return;

  KConfigGroup config = KGlobal::config()->group("General");
  
  hitListWindow = new SearchDlg();
  QSize *defaultSize;
  defaultSize = new QSize(750, 650);
  hitListWindow->resize(config.readEntry("DialogSize", *defaultSize));
  delete defaultSize;
  connect(hitListWindow,SIGNAL(configure()),SLOT(configure()));
  connect(hitListWindow,SIGNAL(readConfiguration()),SLOT(configChanged()));

  hitListWindow->editSearch->setHistoryItems(config.readEntry("History", QStringList()));
  hitListWindow->configChanged();

  sysTrayIcon = new KSystemTrayIcon(hitListWindow);
  QMenu *menu = sysTrayIcon->contextMenu();
  connect(menu,SIGNAL(aboutToShow()),SLOT(aboutToShowSysTrayMenu()));
  connect(menu,SIGNAL(activated(int)),SLOT(historySelected(int)));

  menu->insertSeparator();
  menu->insertItem(SmallIconSet("edit-clear-history"),
                   i18n("Clear Search History"), this,
                   SLOT(clearHistory()),0,HISTORY_ITEMS_CLEAR_ID);

  menu->insertItem(SmallIconSet("configure"),
                   i18n("Configure Kerry..."), this,
                   SLOT(configure()));
/*
  KHelpMenu *helpmenu = new KHelpMenu(hitListWindow, about, false);
  menu->insertItem( SmallIconSet("help"), KStandardGuiItem::help().text(), helpmenu->menu() );
*/
  globalKeys = new KActionCollection(this);

  KAction *a = globalKeys->addAction("show_search_dialog");
  a->setText(i18n("Show Search Dialog"));
  a->setGlobalShortcut(KShortcut(Qt::ALT+Qt::Key_Space));
  connect(a, SIGNAL(triggered()), SLOT(showSearchDialog()));

  a = globalKeys->addAction("search_primary_selection");
  a->setText(i18n("Search Primary Selection"));
  a->setGlobalShortcut(KShortcut(Qt::CTRL+Qt::ALT+Qt::Key_Space));
  connect(a, SIGNAL(triggered()), SLOT(searchPrimarySelection()));

  configChanged();

  sysTrayIcon->setIcon(KIcon("kerry_systemtray"));
//  QToolTip::add(sysTrayIcon, i18n("Kerry Beagle Search (%1)").arg(qobject_cast<KAction*>(globalKeys->action("show_search_dialog"))->globalShortcut().toString()));

  sysTrayIcon->show();

//  sysTrayIcon->actionCollection()->action("file_quit")->setShortcut(KShortcut());
  disconnect(sysTrayIcon->actionCollection()->action("file_quit"), SIGNAL(activated()), sysTrayIcon, SLOT(maybeQuit()));
  connect(sysTrayIcon->actionCollection()->action("file_quit"), SIGNAL(activated()), this, SLOT(quitKerry()));

  QTimer::singleShot( 1000, this, SLOT(checkBeagleBuildIndex()));
}

void KerryApplication::search(const QString& text)
{
  if (hitListWindow)
    hitListWindow->search(text);
}

void KerryApplication::aboutToShowSysTrayMenu()
{
  QMenu *menu = sysTrayIcon->contextMenu();

  for (int id=HISTORY_ITEMS_START_ID;id<=HISTORY_ITEMS_START_ID+MAX_HISTORY_ITEMS;id++)
    menu->removeItem(id);

  QStringList searches = hitListWindow->editSearch->historyItems();
  if (searches.count()==0) {
    menu->insertItem(i18n("<No Recent Searches>"),HISTORY_ITEMS_START_ID,1);
    menu->setItemEnabled(HISTORY_ITEMS_START_ID,false);
    menu->setItemEnabled(HISTORY_ITEMS_CLEAR_ID,false);
    return;
  }

  for (int i=0;i<(int)searches.count();i++)
    menu->insertItem(searches[i],i+HISTORY_ITEMS_START_ID,i+1);
  menu->setItemEnabled(HISTORY_ITEMS_CLEAR_ID,true);
}

void KerryApplication::historySelected(int id)
{
  if (id<HISTORY_ITEMS_START_ID)
    return;

  if (hitListWindow)
    hitListWindow->search(sysTrayIcon->contextMenu()->text(id));
}

void KerryApplication::searchPrimarySelection()
{
  QString text = QApplication::clipboard()->text(QClipboard::Selection);
  if (!text.isEmpty() && hitListWindow)
    hitListWindow->search(text);
}

void KerryApplication::quitKerry()
{
  int autoStart = KMessageBox::questionYesNoCancel( 0L, i18n("Should Kerry start automatically\nwhen you login?"), i18n("Automatically Start Kerry?"), KGuiItem(i18n("&Start")), KGuiItem(i18n("&Do Not Start")) );

  KConfigGroup config = KGlobal::config()->group("General");
  if ( autoStart == KMessageBox::Yes ) {
    config.writeEntry("AutoStart", true);
  } else if ( autoStart == KMessageBox::No) {
    config.writeEntry("AutoStart", false);
  } else  // cancel chosen don't quit
    return;
  config.writeEntry("History",hitListWindow->editSearch->historyItems());
  config.sync();

  if (hitListWindow)
  	hitListWindow->hide();

#ifdef KDELIBS_SUSE
  KProcess *proc = new KProcess;
  *proc << "beagle-shutdown";
  if (!proc->start())
      kDebug() << "Couldn't run beagle-shutdown." << endl;
#endif

  qApp->closeAllWindows();
  qApp->quit();
}

void KerryApplication::clearHistory()
{
   hitListWindow->editSearch->clearHistory();
   KConfigGroup config = KGlobal::config()->group("Default");
   config.writeEntry("History", QStringList());
   config.sync();
}

void KerryApplication::configure()
{
    KProcess proc;
    proc << "kcmshell4";
    proc << "kcmkerry";
    proc.startDetached();
}

void KerryApplication::configChanged()
{
/*    KConfigGroup config = KGlobal::config()->group("Default")
    globalKeys.readSettings(config);
    globalKeys.updateConnections();*/
}

void KerryApplication::checkBeagleBuildIndex()
{
    QDir dir("/tmp", ".beagleindexwapi*");
    dir.setFilter(QDir::Dirs|QDir::Hidden);

    QStringList entryList = dir.entryList();
    if (entryList.isEmpty())
        return;

    bool current_wapidir = false;

    for ( QStringList::Iterator it = entryList.begin(); it != entryList.end(); ++it ) {
        if ( QFileInfo("/tmp/"+(*it)).lastModified().date()==QDate::currentDate() ) {
            current_wapidir=true;
            break;
        }
    }

    if (current_wapidir) {
        KPassivePopup::message(KPassivePopup::Boxed, i18n("System May Be Slower Than Usual"), i18n("The daily process that updates the search index for system documentation\n is running, which may make the system appear slower than usual.\n\nThis process should complete shortly."), BarIcon("info"), sysTrayIcon, 10000);
    }
}

#include "kerryapp.moc"
