/***************************************************************************
                          ksteak.cpp  -  description
                             -------------------
    begin                : Sat Nov 14 2000
    copyright            : (C) 2000, 2001 by Michael Heidecke
    email                : heidecke@web.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "ksteak.h"
#include <qtooltip.h>
#include <kiconloader.h>
#include <kmessagebox.h>
#include <kaccel.h>
#include <kwin.h>
#include <kmenubar.h>
#include <kconfig.h>
#include <klocale.h>
#include <qstring.h>
#include <qcolor.h>
#include "options.h"
#include <kaction.h>
#include <kstdaction.h>
#include <kedittoolbar.h>
#include <kkeydialog.h>

/************************************
 * constructor - main widget        *
 ************************************/
KSteak::KSteak()
	: DCOPObject("KSteakIface"), SteakDock(0)
{
    new KAction( i18n("Start &Search"), "search", CTRL+Key_S, this,SLOT(slotStartSearch()),actionCollection(),"search" );
    new KAction( i18n("&Dock to Panel"), CTRL+Key_D, this, SLOT(slotDock()), actionCollection(), "dock" );
    KStdAction::quit( this, SLOT(slotQuit()), actionCollection() );

    actions.English = new KToggleAction( i18n("&English"), "flag-en", 0, this, SLOT(slotToggleEnglish()), actionCollection(), "english" );
    actions.German = new KToggleAction( i18n("&German"), "flag-de", 0, this, SLOT(slotToggleGerman()), actionCollection(), "german" );
    actions.Context = new KToggleAction( i18n("Show &Context"), "contents2", 0, this, SLOT(slotToggleShowContext()), actionCollection(), "context" );
    actions.Case = new KToggleAction( i18n("Case &sensitive"), "case", 0, this, SLOT(slotToggleCaseSensitive()), actionCollection(), "case_sens" );
    actions.AND = new KToggleAction( i18n("&AND"), "and", 0, this, SLOT(slotToggleAND()), actionCollection(), "and" );
    actions.OR = new KToggleAction( i18n("&OR"), "or", 0, this, SLOT(slotToggleOR()), actionCollection(), "or" );

    actions.showToolbar = KStdAction::showToolbar( this, SLOT(slotShowToolbar()), actionCollection() );
    KStdAction::keyBindings(this, SLOT(slotConfigKeys()), actionCollection());
    KStdAction::configureToolbars(this, SLOT(slotConfigToolbars()), actionCollection());
    KStdAction::preferences( this, SLOT(slotConfigOptions()), actionCollection() );

    actions.inputLine = new KSelectAction("Search Line", CTRL+Key_L, actionCollection(), "line");
    actions.inputLine->setEditable(true);

    connect(actions.inputLine, SIGNAL(activated(const QString &)), this, SLOT(slotAddHistory(const QString &)));
    actions.clearLine = new KAction(i18n("&Clear Line"), "locationbar_erase", CTRL+Key_C, 
									this, SLOT(slotClearLine()), actionCollection(), "clear");

  createGUI();	

  //--- MainWidget ---  
  display = new QTextView(this);
  setCentralWidget(display);	

  SteakDock = new dockwidget();
  SteakDock->setPixmap(BarIcon("ksteak.png"));
  
  connect(SteakDock, SIGNAL(undock()), this, SLOT(slotUndock()));
  connect(SteakDock, SIGNAL(done()), this, SLOT(slotQuit()));
  connect(SteakDock, SIGNAL(configure()), this, SLOT(slotConfigOptions()));
  connect(SteakDock, SIGNAL(translate(const QString &)), this, SLOT(slotTranslateDocked(const QString &)));

  //ga = new KGlobalAccel(); 
  //ga->insertItem( i18n("global translate"), "global translate", "CTRL+T" ); 
  //ga->connectItem( "global translate", this, SLOT( slotTranslate() ) ); 
  //ga->readSettings(); 
    
  //reading config-file
  ReadConfig();
  connect( this, SIGNAL(sigDCOPTranslate(const QString &)), this, SLOT(slotTranslateDCOP(const QString &)) );
}

/*****************************************
 * destructor                            *
 *****************************************/
KSteak::~KSteak()
{
}

/*************************************
 * sort the history (current first)  *
 *************************************/
void KSteak::slotAddHistory(const QString &s)
{
  int i=0;
  QStringList list = actions.inputLine->items();
  QStringList tlist = s;

  for ( QStringList::Iterator it = list.begin(); ((it != list.end()) & (i < 5)); ++it ) 
	if ( (s != (*it) ) & (! (*it).isEmpty()) ) 
	  { 
		tlist += (*it);
		i++;
	  }
  actions.inputLine->setItems(tlist);
  slotTranslateUndocked( s );
}

/***************************************
 * set empty string as current input   *
 ***************************************/
void KSteak::slotClearLine()
{
  int i=0;
  QStringList tlist = "";
  QStringList list = actions.inputLine->items();

  for ( QStringList::Iterator it = list.begin(); ((it != list.end()) & (i < 5)); ++it ) 
	if (! (*it).isEmpty() ) 
	  { 
		tlist += (*it);
		i++;
	  }
  actions.inputLine->setItems(tlist);
}

// --- added by Olaf Hartig (26.Apr.2001)
void KSteak::slotStartSearch()
{
  actions.inputLine->setCurrentItem(0);
  slotTranslateUndocked( actions.inputLine->currentText() );
}

void KSteak::slotToggleEnglish()
{
	_engine._fEnglish = actions.English->isChecked();
}

void KSteak::slotToggleGerman()
{
	_engine._fGerman = actions.German->isChecked();
}

void KSteak::slotToggleShowContext()
{
	_engine._fContext = actions.Context->isChecked();
}

void KSteak::slotToggleCaseSensitive()
{
	_engine._fSensitive = actions.Case->isChecked();
}

void KSteak::slotToggleAND()
{
	_engine._fSearchAnd = actions.AND->isChecked();
	if (actions.AND->isChecked())
	{
		_engine._fSearchOr = false;
		actions.OR->setChecked(false);
	}
}

void KSteak::slotToggleOR()
{
	_engine._fSearchOr = actions.OR->isChecked();
	if (actions.OR->isChecked())
	{
		_engine._fSearchAnd = false;
		actions.AND->setChecked(false);
	}
}

void KSteak::slotShowToolbar()
{
	if (actions.showToolbar->isChecked())
		toolBar("optionsToolBar")->show();
	else
		toolBar("optionsToolBar")->hide();
}

void KSteak::slotConfigToolbars()
{
  KEditToolbar dlg(actionCollection());
  if (dlg.exec()) 
    {
	  // recreate our GUI
	  createGUI();
    }
}

/****************************************
 * Setup Search Options                 *
 ****************************************/
void KSteak::slotConfigOptions()
{
  OptionsDialog *MyDialog = new OptionsDialog(this, "dialog", true);
  if (MyDialog->exec());
}

/****************************************
 * Setup Keys                           *
 ****************************************/
void KSteak::slotConfigKeys()
{
  if( KKeyDialog::configureKeys( actionCollection(), "ksteakui.rc" ) );
}

/***************************************
 * config dialog - apply settings      *
 ***************************************/
void KSteak::applyOptions()
{
  display->setPaper(QBrush::QBrush(bgColor));
  display->setFont(mFont);
  if (! _fDocked)
	{
	  actions.inputLine->setCurrentItem( 0 );
	  slotTranslateUndocked( actions.inputLine->currentText() );
	}
}


/*****************************************
 save Config (state of Toolbar-Buttons)
 *****************************************/
void KSteak::SaveConfig(void)
{
  config = kapp->config();
  config->setGroup("General");
  config->writeEntry("docked", _fDocked);
  config->writeEntry("Size", size());
  _engine.saveStatus( config );
  //save Colors
  config->setGroup("Colors");
  config->writeEntry("TextColor", textColor);
  config->writeEntry("BgColor", bgColor);
  config->writeEntry("Font", mFont);
  //save Combobox history
  config->setGroup("Combobox");
  config->writeEntry("History", actions.inputLine->items());
  //save toolbar state
  config->setGroup("Toolbar");
  config->writeEntry("visible", actions.showToolbar->isChecked() );
  //write config-file
  config->sync();
}

/*****************************************
 read Config
 *****************************************/
void KSteak::ReadConfig(void)
{
  QStringList list;
  QColor *tempColor = new QColor(255,255,150);
  QSize *pSize = new QSize(300,200);
  QFont *pFont = new QFont("helvetica", 12);

  config = kapp->config();
  // General settings
  config->setGroup("General");
  if (config->readBoolEntry("docked")) slotDock();
  else slotUndock();
  // Size
  QSize size = config->readSizeEntry("Size", pSize);
  resize(size);
  actions.English->setChecked( config->readBoolEntry("English") );
  slotToggleEnglish();
  actions.German->setChecked( config->readBoolEntry("German") );
  slotToggleGerman();
  actions.Context->setChecked( config->readBoolEntry("Context") );
  slotToggleShowContext();
  actions.Case->setChecked( config->readBoolEntry("Sensitive") );
  slotToggleCaseSensitive();
  actions.OR->setChecked( config->readBoolEntry("SearchOr") );
  slotToggleOR();
  // Colors + Font
  config->setGroup("Colors");
  textColor = config->readColorEntry("TextColor");        // default black
  bgColor = config->readColorEntry("BgColor", tempColor); // default yellow
  mFont = config->readFontEntry("Font", pFont);           // default helvetica
  display->setPaper(QBrush::QBrush(bgColor));
  display->setFont(mFont);
  // ComboBox History
  config->setGroup("Combobox");
  // list = "";
  list = config->readListEntry("History");
  actions.inputLine->setItems(list);
  // Toolbar options
  config->setGroup("Toolbar");
  actions.showToolbar->setChecked( config->readBoolEntry("visible",true) );
  slotShowToolbar();
}

/*****************************************
 save history before quit
 *****************************************/
void KSteak::slotQuit(void)
{
  SaveConfig();
  kapp->quit();
}


/*****************************************
 session management - save settings
 *****************************************/
void KSteak::saveProperties(KConfig *)
{
  SaveConfig();
}


/*****************************************
 show dockwidget + hide mainwidget
 *****************************************/
void KSteak::slotDock(void)
{
  SteakDock->show();
  this->hide();
  _fDocked = true;
}

/*****************************************
 hide dockwidget + show mainwidget
 *****************************************/
void KSteak::slotUndock(void)
{
  setActiveWindow();
  this->raise();
  this->show();

  if ( _fDocked )
    {
      SteakDock->hide();
      _fDocked = false;
    }
}


void KSteak::slotTranslateUndocked( const QString & szWord )
{
  /* initialize display (font color) */
  display->setText("<qt text="+textColor.name()+">");
  /* get translation */
  _engine.translate( szWord, display);
}


void KSteak::slotTranslateDocked( const QString & szWord )
{
  /* initialize display (font + colors) */
  SteakDock->myview->setPaper(QBrush::QBrush(bgColor));
  SteakDock->mypop->setFont(mFont);
  SteakDock->myview->setText("<qt text="+textColor.name()+">");
  /* get translation */
  _engine.translatePopup( szWord, SteakDock->myview );
}

void KSteak::slotTranslateDCOP( const QString & szWord )
{
   if ( _fDocked )
     SteakDock->getTranslation( szWord );
   else
    {  
	  setActiveWindow();
	  this->raise();
	  this->show();  // this is needed by QTextView (to change context)
	  slotAddHistory( szWord );
    }
}

void KSteak::translate(const QString & szWord)
{
    emit sigDCOPTranslate(szWord);
}

void KSteak::dock()
{
    slotDock();
}

void KSteak::undock()
{
    slotUndock();
}

