/***************************************************************************
 *   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 <tqstring.h>
#include <tqstringlist.h>
#include <tqdir.h>
#include <tqclipboard.h>
#include <tdefiledialog.h>
#include <tdecmdlineargs.h>
#include <fcntl.h>
#include <tdelocale.h>
#include <tdemessagebox.h>
#include <kdebug.h>
#include <khelpmenu.h>
#include <kprocess.h>

#include <tqtooltip.h>
#include <tqdom.h>
#include <tqtimer.h>

#include "searchdlg.h"
#include "kerryapp.h"
#include <tdeaction.h>
#include <tdepopupmenu.h>
#include <kiconloader.h>
#include <klineedit.h>
#include <kprocess.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) {
    TDEConfig *config = TDEGlobal::config();
    config->writeEntry("History",hitListWindow->editSearch->historyItems());
    config->writeEntry("DialogSize",hitListWindow->size());
    config->sync();

    delete hitListWindow;
  }
}

int KerryApplication::newInstance()
{
    if (!hitListWindow)
        init(TDEGlobal::instance()->aboutData());

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

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

        args->clear();

    return KUniqueApplication::newInstance();
}

void KerryApplication::init(const TDEAboutData* /*about*/)
{
  if (hitListWindow)
      return;

  TDEConfig *config = TDEGlobal::config();
  config->setGroup("General");

  hitListWindow = new SearchDlg();
  TQSize *defaultSize;
  defaultSize = new TQSize(750, 650);
  hitListWindow->resize(config->readSizeEntry("DialogSize", defaultSize));
  delete defaultSize;
  connect(hitListWindow,TQT_SIGNAL(configure()),TQT_SLOT(configure()));
  connect(hitListWindow,TQT_SIGNAL(readConfiguration()),TQT_SLOT(configChanged()));

  hitListWindow->editSearch->setHistoryItems(config->readListEntry("History"));
  hitListWindow->configChanged();

  sysTrayIcon = new KSystemTray(hitListWindow);
  TDEPopupMenu *menu = sysTrayIcon->contextMenu();
  connect(menu,TQT_SIGNAL(aboutToShow()),TQT_SLOT(aboutToShowSysTrayMenu()));
  connect(menu,TQT_SIGNAL(activated(int)),TQT_SLOT(historySelected(int)));

  menu->insertSeparator();
  menu->insertItem(SmallIconSet("history_clear"),
                   i18n("Clear Search History"), this,
                   TQT_SLOT(clearHistory()),0,HISTORY_ITEMS_CLEAR_ID);

  menu->insertItem(SmallIconSet("configure"),
                   i18n("Configure Kerry..."), this,
                   TQT_SLOT(configure()));
/*
  KHelpMenu *helpmenu = new KHelpMenu(hitListWindow, about, false);
  menu->insertItem( SmallIconSet("help"), KStdGuiItem::help().text(), helpmenu->menu() );
*/
  globalKeys = new TDEGlobalAccel(TQT_TQOBJECT(this));
  globalKeys->insert( "Program:kerry", i18n("Kerry Beagle Search") );

  TDEShortcut showDialogShortcut = TDEShortcut(ALT+Key_Space);
  showDialogShortcut.append( KKey( Key_F12 ) );
  globalKeys->insert( "Show Kerry Dialog", i18n("Show Search Dialog"), TQString(), showDialogShortcut, showDialogShortcut, TQT_TQOBJECT(hitListWindow), TQT_SLOT(showSearchDialog()) );
  globalKeys->insert( "Search Primary Selection with Kerry", i18n("Search Primary Selection"), TQString(), CTRL+ALT+Key_Space, CTRL+ALT+Key_Space, TQT_TQOBJECT(this), TQT_SLOT(searchPrimarySelection()) );
  configChanged();

  sysTrayIcon->setPixmap(sysTrayIcon->loadIcon("kerry_systemtray"));
  TQToolTip::add(sysTrayIcon, i18n("Kerry Beagle Search (%1)").arg(globalKeys->shortcut("Show Kerry Dialog").seq(0).toString()));

  sysTrayIcon->show();

  sysTrayIcon->actionCollection()->action("file_quit")->setShortcut(TDEShortcut());
  disconnect(sysTrayIcon->actionCollection()->action("file_quit"), TQT_SIGNAL(activated()), sysTrayIcon, TQT_SLOT(maybeQuit()));
  connect(sysTrayIcon->actionCollection()->action("file_quit"), TQT_SIGNAL(activated()), TQT_TQOBJECT(this), TQT_SLOT(quitKerry()));

  TQTimer::singleShot( 1000, TQT_TQOBJECT(this), TQT_SLOT(checkBeagleBuildIndex()));
}

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

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

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

  TQStringList 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()
{
  TQApplication::clipboard()->setSelectionMode( true );
  TQString text = TQApplication::clipboard()->text();
  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?"), i18n("&Start"), i18n("&Do Not Start") );

  TDEConfig *config = TDEGlobal::config();
  config->setGroup("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
  TDEProcess *proc = new TDEProcess;
  *proc << "beagle-shutdown";
  if (!proc->start())
      kdDebug() << "Couldn't run beagle-shutdown." << endl;
#endif

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

void KerryApplication::clearHistory()
{
   hitListWindow->editSearch->clearHistory();
   TDEConfig *config = TDEGlobal::config();
   config->writeEntry("History",TQString());
   config->sync();
}

void KerryApplication::configure()
{
    TDEProcess proc;
    proc << "tdecmshell";
    proc << "kcmkerry.desktop";
    proc.start(TDEProcess::DontCare);
}

void KerryApplication::configChanged()
{
    TDEConfig *config = TDEGlobal::config();
    globalKeys->readSettings(config);
    globalKeys->updateConnections();
}

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

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

    bool current_wapidir = false;

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

    TQString oldMessage = I18N_NOOP("The daily running process for updating the system\nwide Beagle documentation index was detected.");
    TQString message;

    if (oldMessage==i18n(oldMessage.ascii()))
        message = "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.";
    else
        message = i18n(oldMessage.ascii());

    if (current_wapidir)
        KPassivePopup::message(KPassivePopup::Boxed, i18n("System May Be Slower Than Usual"), message, BarIcon("application-vnd.tde.info"), sysTrayIcon, 0, 10000);
}

#include "kerryapp.moc"
