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

/*
  Copyright (C) 2006 Dario Abatianni <eisfuchs@tigress.com>
  Copyright (C) 2006 John Tapsell <johnflux@gmail.com>
*/

#include "highlight_preferences.h"
#include "highlightviewitem.h"
#include "konversationapplication.h"
#include "konversationsound.h"

#include <tqdir.h>
#include <tqlabel.h>
#include <tqheader.h>
#include <tqtooltip.h>
#include <tqtoolbutton.h>

#include <tdeglobal.h>
#include <kstandarddirs.h>
#include <kurlrequester.h>
#include <tdefiledialog.h>
#include <tdelistview.h>
#include <klineedit.h>
#include <kcolorbutton.h>
#include <tdelocale.h>
#include <tdeparts/componentfactory.h>
#include <kregexpeditorinterface.h>
#include <kiconloader.h>


Highlight_Config::Highlight_Config(TQWidget* parent, const char* name)
 : Highlight_ConfigUI(parent,name)
{
  // reset flag to defined state (used to block signals when just selecting a new item)
  newItemSelected=false;

  loadSettings();

  // make list accept drag & drop
  highlightListView->setSorting(-1);
  highlightListView->header()->setMovingEnabled(false);

  soundPlayBtn->setIconSet(SmallIconSet( "media-playback-start" ));
  soundURL->setCaption(i18n("Select Sound File"));

  // This code was copied from KNotifyWidget::openSoundDialog() (knotifydialog.cpp) [it's under LGPL v2]
  // find the first "sound"-resource that contains files
  TQStringList soundDirs = TDEGlobal::dirs()->findDirs("data", "konversation/sounds");
  soundDirs += TDEGlobal::dirs()->resourceDirs( "sound" );

  if ( !soundDirs.isEmpty() ) {
    KURL url;
    TQDir dir;
    dir.setFilter( TQDir::Files | TQDir::Readable );
    TQStringList::ConstIterator it = soundDirs.begin();
    while ( it != soundDirs.end() ) {
      dir = *it;
      if ( dir.isReadable() && dir.count() > 2 ) {
        url.setPath( *it );
       soundURL->fileDialog()->setURL( url );
        break;
      }
      ++it;
    }
  }
  // End copy

  connect(highlightListView,TQ_SIGNAL (selectionChanged(TQListViewItem*)),this,TQ_SLOT (highlightSelected(TQListViewItem*)) );
  connect(highlightListView,TQ_SIGNAL (clicked(TQListViewItem*)),this,TQ_SLOT (highlightSelected(TQListViewItem*)) );
  connect(highlightListView,TQ_SIGNAL (spacePressed(TQListViewItem*)),this,TQ_SLOT (highlightSelected(TQListViewItem*)) );

  connect(highlightListView,TQ_SIGNAL (moved()),this,TQ_SIGNAL (modified()) );

  connect(patternInput,TQ_SIGNAL (textChanged(const TQString&)),this,TQ_SLOT (highlightTextChanged(const TQString&)) );
  connect(patternButton,TQ_SIGNAL (clicked()),this,TQ_SLOT(highlightTextEditButtonClicked()));
  connect(patternColor,TQ_SIGNAL (changed(const TQColor&)),this,TQ_SLOT (highlightColorChanged(const TQColor&)) );

  connect(soundURL, TQ_SIGNAL(textChanged(const TQString&)), this, TQ_SLOT(soundURLChanged(const TQString&)));
  connect(soundPlayBtn, TQ_SIGNAL(clicked()), this, TQ_SLOT(playSound()));

  connect(autoTextInput,TQ_SIGNAL (textChanged(const TQString&)),this,TQ_SLOT (autoTextChanged(const TQString&)) );

  connect(newButton,TQ_SIGNAL (clicked()),this,TQ_SLOT (addHighlight()) );
  connect(removeButton,TQ_SIGNAL (clicked()),this,TQ_SLOT (removeHighlight()) );

  updateButtons();
}

Highlight_Config::~Highlight_Config()
{
}

void Highlight_Config::restorePageToDefaults()
{
  if(highlightListView->childCount() != 0) {
    highlightListView->clear();
    emit modified();
  }
}

void Highlight_Config::loadSettings()
{
  TQPtrList<Highlight> highlightList=Preferences::highlightList();
  highlightListView->clear();
  // fill in the highlight patterns backwards to keep the right sorting order
  for(unsigned int i=highlightList.count();i!=0;i--)
  {
    Highlight* currentHighlight=highlightList.at(i-1);
    new HighlightViewItem(highlightListView,currentHighlight);
  }

  highlightListView->setSelected(highlightListView->firstChild(), true);

  // remember current list for hasChanged()
  m_oldHighlightList=currentHighlightList();
}

bool Highlight_Config::hasChanged()
{
  return(m_oldHighlightList!=currentHighlightList());
}

// Slots:

void Highlight_Config::highlightSelected(TQListViewItem* item)
{
  // check if there was a widget selected at all
  if(item)
  {
    // make a highlight item out of the generic qlistviewitem
    HighlightViewItem* highlightItem=static_cast<HighlightViewItem*>(item);

    // check if the checkbox on the item has changed
    if(highlightItem->hasChanged())
    {
      // tell the prefs system it was changed and acknowledge the change to the listview item
      emit modified();
      highlightItem->changeAcknowledged();
    }

    // tell all now emitted signals that we just clicked on a new item, so they should
    // not emit the modified() signal.
    newItemSelected=true;
   patternColor->setColor(highlightItem->getColor());
   patternInput->setText(highlightItem->getPattern());
   soundURL->setURL(highlightItem->getSoundURL().prettyURL());
   autoTextInput->setText(highlightItem->getAutoText());
    // all signals will now emit the modified() signal again
    newItemSelected=false;
    // remember to enable all edit widgets
  }
  updateButtons();

 }

void Highlight_Config::updateButtons()
{
  bool enabled = highlightListView->selectedItem() != NULL;
  // is the kregexpeditor installed?
  bool installed = !TDETrader::self()->query("KRegExpEditor/KRegExpEditor").isEmpty();
  // enable or disable edit widgets
  patternLabel->setEnabled(enabled);
  patternInput->setEnabled(enabled);
  patternButton->setEnabled(enabled && installed);
  colorLabel->setEnabled(enabled);
  patternColor->setEnabled(enabled);
  soundURL->setEnabled(enabled);
  soundLabel->setEnabled(enabled);
  soundPlayBtn->setEnabled(enabled);
  autoTextLabel->setEnabled(enabled);
  autoTextInput->setEnabled(enabled);

  if(installed)
  {
      TQToolTip::add(patternButton, i18n("Click to run Regular Expression Editor (KRegExpEditor)"));
  }
  else
  {
      TQToolTip::add(patternButton, i18n("The Regular Expression Editor (KRegExpEditor) is not installed"));
  }
}

void Highlight_Config::highlightTextChanged(const TQString& newPattern)
{
  HighlightViewItem* item=static_cast<HighlightViewItem*>(highlightListView->selectedItem());

  if(!newItemSelected && item)
  {
    item->setPattern(newPattern);
    emit modified();
  }
}

void Highlight_Config::highlightTextEditButtonClicked()
{
  TQDialog *editorDialog =
      KParts::ComponentFactory::createInstanceFromQuery<TQDialog>( "KRegExpEditor/KRegExpEditor" );
  if (editorDialog)
  {
        // tdeutils was installed, so the dialog was found.  Fetch the editor interface.
    KRegExpEditorInterface *reEditor =
        static_cast<KRegExpEditorInterface *>(editorDialog->tqt_cast( "KRegExpEditorInterface" ) );
    Q_ASSERT( reEditor ); // This should not fail!// now use the editor.
    reEditor->setRegExp(patternInput->text());
    int dlgResult = editorDialog->exec();
    if ( dlgResult == TQDialog::Accepted )
    {
      TQString re = reEditor->regExp();
      patternInput->setText(re);
      HighlightViewItem* item=static_cast<HighlightViewItem*>(highlightListView->selectedItem());
      if(item) item->setPattern(re);
    }
    delete editorDialog;
  }
}

void Highlight_Config::highlightColorChanged(const TQColor& newColor)
{
  HighlightViewItem* item=static_cast<HighlightViewItem*>(highlightListView->selectedItem());

  if(!newItemSelected && item)
  {
    item->setColor(newColor);
    item->repaint();
    emit modified();
  }
}

void Highlight_Config::soundURLChanged(const TQString& newURL)
{
  HighlightViewItem* item=static_cast<HighlightViewItem*>(highlightListView->selectedItem());

  if(!newItemSelected && item)
  {
    item->setSoundURL(KURL(newURL));
    emit modified();
  }
}

void Highlight_Config::autoTextChanged(const TQString& newText)
{
  HighlightViewItem* item=static_cast<HighlightViewItem*>(highlightListView->selectedItem());

  if(!newItemSelected && item)
  {
    item->setAutoText(newText);
    emit modified();
  }
}

void Highlight_Config::addHighlight()
{
  Highlight* newHighlight=new Highlight(i18n("New"),false,TQColor("#ff0000"),KURL(),TQString());

  HighlightViewItem* item=new HighlightViewItem(highlightListView,newHighlight);
  highlightListView->setSelected(item,true);
  patternInput->setFocus();
  patternInput->selectAll();
  emit modified();
}

void Highlight_Config::removeHighlight()
{
  HighlightViewItem* item=static_cast<HighlightViewItem*>(highlightListView->selectedItem());

  if(item)
  {
    delete item;

    item=static_cast<HighlightViewItem*>(highlightListView->currentItem());

    if(item)
      highlightListView->setSelected(item,true);

    emit modified();
  }
  updateButtons();
}

TQPtrList<Highlight> Highlight_Config::getHighlightList()
{
  TQPtrList<Highlight> newList;

  HighlightViewItem* item=static_cast<HighlightViewItem*>(highlightListView->firstChild());
  while(item)
  {
    newList.append(new Highlight(item->getPattern(),item->getRegExp(),item->getColor(),item->getSoundURL(),item->getAutoText()));
    item=item->itemBelow();
  }

  return newList;
}

TQStringList Highlight_Config::currentHighlightList()
{
  TQStringList newList;

  HighlightViewItem* item=static_cast<HighlightViewItem*>(highlightListView->firstChild());
  while(item)
  {
    newList.append(item->getPattern()+item->getRegExp()+item->getColor().name()+item->getSoundURL().url()+item->getAutoText());
    item=item->itemBelow();
  }

  return newList;
}

void Highlight_Config::playSound()
{
  KonversationApplication *konvApp=static_cast<KonversationApplication *>(TDEApplication::kApplication());
  konvApp->sound()->play(KURL(soundURL->url()));
}

void Highlight_Config::saveSettings()
{
  TDEConfig* config = kapp->config();

  // Write all highlight entries
  TQPtrList<Highlight> hiList=getHighlightList();
  int i = 0;
  for(Highlight* hl = hiList.first(); hl; hl = hiList.next())
  {
    config->setGroup(TQString("Highlight%1").arg(i));
    config->writeEntry("Pattern", hl->getPattern());
    config->writeEntry("RegExp", hl->getRegExp());
    config->writeEntry("Color", hl->getColor());
    config->writePathEntry("Sound", hl->getSoundURL().prettyURL());
    config->writeEntry("AutoText", hl->getAutoText());
    i++;
  }

  Preferences::setHighlightList(hiList);

  // Remove unused entries...
  while(config->hasGroup(TQString("Highlight%1").arg(i)))
  {
    config->deleteGroup(TQString("Highlight%1").arg(i));
    i++;
  }

  // remember current list for hasChanged()
  m_oldHighlightList=currentHighlightList();
}

#include "highlight_preferences.moc"
