/***************************************************************************
                          knewprojectdlg.cpp  -  description
                             -------------------
    begin                : Tue Dec 28 1999
    copyright            : (C) 1999 by François Dupoux
                           (C) 2004 Emiliano Gulmini <emi_barbarossa@yahoo.it>
    email                : dupoux@dupoux.com
 ***************************************************************************/

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


//QT
#include <tqwhatsthis.h>
#include <tqcheckbox.h>
#include <tqspinbox.h>
#include <tqdatetimeedit.h>
#include <tqlabel.h>
#include <tqradiobutton.h>
#include <tqtextedit.h>
#include <tqlistview.h>

//KDE
#include <kseparator.h>
#include <tdemessagebox.h>
#include <kcharsets.h>
#include <kcombobox.h>
#include <tdeconfig.h>
#include <tdefiledialog.h>
#include <klineedit.h>
#include <tdeglobal.h>
#include <tdelocale.h>
#include <kpushbutton.h>
#include <kstandarddirs.h>
#include <tdeversion.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <tdeapplication.h>

// local
#include "knewprojectdlg.h"
#include "whatthis.h"

using namespace whatthisNameSpace;


KNewProjectDlg::KNewProjectDlg(RCOptions* info, TQWidget *parent, const char *name) : KNewProjectDlgS(parent, name)
{
  m_searchNowFlag = "";
  m_option = info;

  initGUI();

  connect(m_chbIncludeSubfolders, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(slotEnableMaxDepthControls(bool)));
  connect(m_chbLimitDepth, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(slotEnableSpinboxMaxDepth(bool)));
  connect(m_pbLocation, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotDir()));
  connect(m_pbCancel, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotReject()));
  connect(m_pbSearchNow, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotSearchNow()));
  connect(m_pbSearchLater, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotSearchLater()));
  connect(m_cbSearch, TQ_SIGNAL(textChanged(const TQString&)), this, TQ_SLOT(slotSearchLineEdit(const TQString&)));
  connect(m_chbSizeMin, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(slotEnableSpinboxSizeMin(bool)));
  connect(m_chbSizeMax, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(slotEnableSpinboxSizeMax(bool)));
  connect(m_chbDateMin, TQ_SIGNAL(toggled(bool)), m_dedDateMin, TQ_SLOT(setEnabled(bool)));
  connect(m_chbDateMax, TQ_SIGNAL(toggled(bool)), m_dedDateMax, TQ_SLOT(setEnabled(bool)));
  connect(m_chbDateMin,TQ_SIGNAL(toggled(bool)),this, TQ_SLOT(slotEnableCbValidDate(bool)));
  connect(m_chbDateMax,TQ_SIGNAL(toggled(bool)),this, TQ_SLOT(slotEnableCbValidDate(bool)));
  connect(m_chbOwnerUser, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(slotEnableChbUser(bool)));
  connect(m_chbOwnerGroup, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(slotEnableChbGroup(bool)));
  connect(m_chbBackup, TQ_SIGNAL(toggled(bool)), this, TQ_SLOT(slotEnableChbBackup(bool)));
  connect(m_pbHelp, TQ_SIGNAL(clicked()), this, TQ_SLOT(slotHelp()));

  whatsThis();
}

KNewProjectDlg::~KNewProjectDlg()
{
}

void KNewProjectDlg::saveRCOptions()
{
  saveOptions();
  saveFileSizeOptions();
  saveDateAccessOptions();
  saveOwnerOptions();
  saveCBLists();
  saveFiltersList();
  saveBackupExtensionOptions();
}

void KNewProjectDlg::slotDir()
{
  TQString directoryString = KFileDialog::getExistingDirectory(TQString(), this, i18n("Project Directory"));
  if(!directoryString.isEmpty())
    m_cbLocation->setEditText(directoryString);
}

void KNewProjectDlg::slotOK()
{
   // Check that Search text and Filter are not empty
   if(!m_cbSearch->currentText().isEmpty())
     {
       if(m_cbReplace->currentText().isEmpty())
         m_option->m_searchingOnlyMode = true;
       else
         m_option->m_searchingOnlyMode = false;
     }
   m_option->m_quickSearchString = m_searchNowFlag + m_cbSearch->currentText();
   m_option->m_quickReplaceString = m_searchNowFlag + m_cbReplace->currentText();

   if (m_cbLocation->currentText().isEmpty() || m_cbFilter->currentText().isEmpty())
     {
       KMessageBox::error(this, i18n("You must fill the combo boxes (location and filter) before continuing."));
       return;
     }

   //  OWNER OPTIONS
   if ((m_chbOwnerUser->isChecked() && m_edOwnerUser->text().isEmpty()) ||
       (m_chbOwnerGroup->isChecked() && m_edOwnerGroup->text().isEmpty()))
   {
      KMessageBox::error(this, i18n("Some edit boxes are empty in the <b>Owner</b> page."));
      return ;
   }

   // Check option "Size Min/Max": check MinSize is not greater than MaxSize
   int minSize = m_spbSizeMin->value(),
       maxSize = m_spbSizeMax->value();
   if ((minSize != FileSizeOption) && (maxSize != FileSizeOption))
    if (minSize > maxSize)
   {
      KMessageBox::error(this, i18n("The minimum size is greater than the maximum size."));
      return ;
   }

  accept();
}

void KNewProjectDlg::slotReject()
{
  m_option->m_quickSearchString = m_searchNowFlag;
  m_option->m_quickReplaceString = m_searchNowFlag;

  reject();
}

void KNewProjectDlg::slotSearchNow()
{ //Add a 'N' to represent the status search-now
  m_searchNowFlag = "N";
  slotOK();
}

void KNewProjectDlg::slotSearchLater()
{ //Add a 'L' to represent the status search-later
  m_searchNowFlag = "L";
  slotOK();
}

void KNewProjectDlg::slotSearchLineEdit(const TQString& t)
{
  m_pbSearchNow->setEnabled(!t.isEmpty());
  m_pbSearchLater->setEnabled(!t.isEmpty());
}

void KNewProjectDlg::slotEnableSpinboxSizeMin(bool b)
{
  m_spbSizeMin->setEnabled(b);
}

void KNewProjectDlg::slotEnableSpinboxSizeMax(bool b)
{
  m_spbSizeMax->setEnabled(b);
}

void KNewProjectDlg::slotEnableSpinboxMaxDepth(bool b)
{
  m_spbMaxDepth->setEnabled(b);
}

void KNewProjectDlg::slotEnableMaxDepthControls(bool b)
{
  m_chbLimitDepth->setEnabled(b);
  m_spbMaxDepth->setEnabled(b && m_chbLimitDepth->isChecked());
}

void KNewProjectDlg::slotEnableCbValidDate(bool b)
{
  Q_UNUSED(b);
  m_cbDateValid->setEnabled(m_chbDateMax->isChecked() || m_chbDateMin->isChecked());
}

void KNewProjectDlg::slotEnableChbUser(bool b)
{
  m_cbOwnerUserType->setEnabled(b);
  m_cbOwnerUserBool->setEnabled(b);
  m_edOwnerUser->setEnabled(b);
}

void KNewProjectDlg::slotEnableChbGroup(bool b)
{
  m_cbOwnerGroupType->setEnabled(b);
  m_cbOwnerGroupBool->setEnabled(b);
  m_edOwnerGroup->setEnabled(b);
}

void KNewProjectDlg::slotEnableChbBackup(bool b)
{
  m_leBackup->setEnabled(b);
  m_tlBackup->setEnabled(b);
}

//PRIVATE
void KNewProjectDlg::initGUI()
{
  TQIconSet iconSet = SmallIconSet("document-open");
  TQPixmap pixMap = iconSet.pixmap( TQIconSet::Small, TQIconSet::Normal );

  m_pbLocation->setIconSet(iconSet);
  m_pbLocation->setFixedSize(pixMap.width() + 8, pixMap.height() + 8);

  m_pbSearchNow->setEnabled(false);
  m_pbSearchLater->setEnabled(false);

  loadOptions();
  loadFileSizeOptions();
  loadDateAccessOptions();
  loadOwnerOptions();
  loadBackupExtensionOptions();
  loadCBLists();
  loadFiltersList();
  
  m_cbSearch->setFocus();
}

void KNewProjectDlg::loadOptions()
{
  TQStringList availableEncodingNames(TDEGlobal::charsets()->availableEncodingNames());
  m_cbEncoding->insertStringList(availableEncodingNames);
  int idx = -1;
  int utf8Idx = -1;
  for (uint i = 0; i < availableEncodingNames.count(); i++)
  {
    if (availableEncodingNames[i] == m_option->m_encoding)
    {
      idx = i;
      break;
    }
    if (availableEncodingNames[i] == "utf8")
    {
      utf8Idx = i;
    }
  }
  if (idx != -1)
    m_cbEncoding->setCurrentItem(idx);
  else 
    m_cbEncoding->setCurrentItem(utf8Idx);
    
  m_chbIncludeSubfolders->setChecked(m_option->m_recursive);
  m_chbCaseSensitive->setChecked(m_option->m_caseSensitive);
  m_chbEnableVariables->setChecked(m_option->m_variables);
  m_chbRegularExpressions->setChecked(m_option->m_regularExpressions);
  m_chbLimitDepth->setEnabled(m_option->m_recursive);
  m_chbLimitDepth->setChecked(m_option->m_limitDepth);
  m_spbMaxDepth->setEnabled(m_option->m_recursive && m_option->m_limitDepth);
  m_spbMaxDepth->setValue(m_option->m_maxDepth);
}

void KNewProjectDlg::loadFileSizeOptions()
{
  int size = m_option->m_minSize;
  if(size == FileSizeOption)
    {
      m_chbSizeMin->setChecked(false);
      m_spbSizeMin->setEnabled(false);
      m_spbSizeMin->setValue(0);
    }
  else
    {
      m_chbSizeMin->setChecked(true);
      m_spbSizeMin->setEnabled(true);
      m_spbSizeMin->setValue(size);
    }

  size = m_option->m_maxSize;
  if(size == FileSizeOption)
    {
      m_chbSizeMax->setChecked(false);
      m_spbSizeMax->setEnabled(false);
      m_spbSizeMax->setValue(0);
    }
  else
    {
      m_chbSizeMax->setChecked(true);
      m_spbSizeMax->setEnabled(true);
      m_spbSizeMax->setValue(size);
    }
}

void KNewProjectDlg::loadDateAccessOptions()
{
  // ================== DATE OPTIONS ========================

  TQString date = m_option->m_minDate;
  if(date == AccessDateOption)
    {
      m_chbDateMin->setChecked(false);
      m_dedDateMin->setDate(m_dedDateMin->minValue());
      m_dedDateMin->setEnabled(false);
    }
  else
    {
      m_chbDateMin->setChecked(true);
      m_dedDateMin->setDate(TQDate::fromString(date,TQt::ISODate));
      m_dedDateMin->setEnabled(true);
    }

  date = m_option->m_maxDate;
  if(date == AccessDateOption)
    {
      m_chbDateMax->setChecked(false);
      m_dedDateMax->setDate(m_dedDateMax->maxValue());
      m_dedDateMax->setEnabled(false);
    }
  else
    {
      m_chbDateMax->setChecked(true);
      m_dedDateMax->setDate(TQDate::fromString(date,TQt::ISODate));
      m_dedDateMax->setEnabled(true);
    }

  m_cbDateValid->setEnabled(m_chbDateMax->isChecked() || m_chbDateMin->isChecked());

}

void KNewProjectDlg::loadOwnerOptions()
{
  bool enableOwner = m_option->m_ownerUserIsChecked;

  m_chbOwnerUser->setChecked(enableOwner);
  m_cbOwnerUserType->setEnabled(enableOwner);
  m_cbOwnerUserBool->setEnabled(enableOwner);
  m_edOwnerUser->setEnabled(enableOwner);

  m_cbOwnerUserType->setCurrentText(m_option->m_ownerUserType);
  m_cbOwnerUserBool->setCurrentText(m_option->m_ownerUserBool);

  m_edOwnerUser->setText(m_option->m_ownerUserValue);

  enableOwner = m_option->m_ownerGroupIsChecked;

  m_chbOwnerGroup->setChecked(enableOwner);
  m_cbOwnerGroupType->setEnabled(enableOwner);
  m_cbOwnerGroupBool->setEnabled(enableOwner);
  m_edOwnerGroup->setEnabled(enableOwner);

  m_cbOwnerGroupType->setCurrentText(m_option->m_ownerGroupType);
  m_cbOwnerGroupBool->setCurrentText(m_option->m_ownerGroupBool);
  m_edOwnerGroup->setText(m_option->m_ownerGroupValue);
}

void KNewProjectDlg::loadCBLists()
{
  m_cbSearch->insertStringList(m_option->m_searchStrings);
  m_cbReplace->insertStringList(m_option->m_replaceStrings);
  m_cbLocation->insertStringList(m_option->m_directories);
  slotSearchLineEdit(m_cbSearch->currentText());
}

void KNewProjectDlg::loadFiltersList()
{
  m_cbFilter->insertStringList(m_option->m_filters);
}

void KNewProjectDlg::loadBackupExtensionOptions()
{
  bool enableBackup = m_option->m_backup;

  m_chbBackup->setChecked(enableBackup);
  m_leBackup->setEnabled(enableBackup);
  m_tlBackup->setEnabled(enableBackup);
  m_leBackup->setText(m_option->m_backupExtension);
}

void KNewProjectDlg::saveOptions()
{
  m_option->m_encoding = m_cbEncoding->currentText();
  m_option->m_recursive = m_chbIncludeSubfolders->isChecked();
  m_option->m_caseSensitive = m_chbCaseSensitive->isChecked();
  m_option->m_variables = m_chbEnableVariables->isChecked();
  m_option->m_regularExpressions = m_chbRegularExpressions->isChecked();
  m_option->m_limitDepth = m_chbLimitDepth->isChecked();
  m_option->m_maxDepth = m_spbMaxDepth->value();
  
}

void KNewProjectDlg::saveFileSizeOptions()
{
  if(m_chbSizeMax->isChecked())
    m_option->m_maxSize = m_spbSizeMax->value();
  else
    m_option->m_maxSize = FileSizeOption;

  if(m_chbSizeMin->isChecked())
    m_option->m_minSize = m_spbSizeMin->value();
  else
    m_option->m_minSize = FileSizeOption;
}

void KNewProjectDlg::saveDateAccessOptions()
{
  if(m_chbDateMin->isChecked() || m_chbDateMax->isChecked())
    m_option->m_dateAccess = m_cbDateValid->currentText();
  else
    m_option->m_dateAccess = ValidAccessDateOption;

  if(m_chbDateMin->isChecked())
    {
      TQString date = m_dedDateMin->date().toString(TQt::ISODate);
      m_option->m_minDate = date;
    }
  else
    m_option->m_minDate = AccessDateOption;

  if(m_chbDateMax->isChecked())
    {
      TQString date = m_dedDateMax->date().toString(TQt::ISODate);
      m_option->m_maxDate = date;
    }
  else
    m_option->m_maxDate = AccessDateOption;
}

void KNewProjectDlg::saveOwnerOptions()
{
  bool isChecked = m_chbOwnerUser->isChecked();
  if(isChecked)
    {
      m_option->m_ownerUserIsChecked = true;
      m_option->m_ownerUserType = m_cbOwnerUserType->currentText();
      m_option->m_ownerUserBool = m_cbOwnerUserBool->currentText();
      m_option->m_ownerUserValue = m_edOwnerUser->text();
    }
  else
    {
      m_option->m_ownerUserIsChecked = false;
      m_option->m_ownerUserType = "Name";
      m_option->m_ownerUserBool = "Equals To";
      m_option->m_ownerUserValue = "";
    }

  isChecked = m_chbOwnerGroup->isChecked();
  if(isChecked)
    {
      m_option->m_ownerGroupIsChecked = true;
      m_option->m_ownerGroupType = m_cbOwnerGroupType->currentText();
      m_option->m_ownerGroupBool = m_cbOwnerGroupBool->currentText();
      m_option->m_ownerGroupValue = m_edOwnerGroup->text();
    }
  else
    {
      m_option->m_ownerGroupIsChecked = false;
      m_option->m_ownerGroupType = "Name";
      m_option->m_ownerGroupBool = "Equals To";
      m_option->m_ownerGroupValue = "";
    }
}

void KNewProjectDlg::saveCBLists()
{
  // Search list
  TQString current = m_cbSearch->currentText();
  m_option->m_searchStrings.clear();
  m_option->m_searchStrings.append(current);
  int count = m_cbSearch->listBox()->count();
  for (int i = 0; i < count; ++i)
    {
      TQString text = m_cbSearch->listBox()->item(i)->text();
      if (text != "" && text != current)
        m_option->m_searchStrings.append(text);
    }
  
  // Replace list
  current = m_cbReplace->currentText();
  m_option->m_replaceStrings.clear();
  m_option->m_replaceStrings.append(current);
  count = m_cbReplace->listBox()->count();
  for (int i = 0; i < count; ++i)
    {
      TQString text = m_cbReplace->listBox()->item(i)->text();
      if (text != "" && text != current)
        m_option->m_replaceStrings.append(text);
    }
  
  // Location list
  current = m_cbLocation->currentText();
  m_option->m_directories.clear();
  m_option->m_directories.append(current);
  count = m_cbLocation->listBox()->count();
  for (int i = 0; i < count; ++i)
    {
      TQString text = m_cbLocation->listBox()->item(i)->text();
      if (text != "" && text != current)
        m_option->m_directories.append(text);
    }
}

void KNewProjectDlg::saveFiltersList()
{
  TQString current = m_cbFilter->currentText();
  TQStringList list = current;

  int count = m_cbFilter->listBox()->count(),
      i;
  for(i = 0; i < count; i++)
    {
      TQString text =  m_cbFilter->listBox()->item(i)->text();
      if(text != current)
        list.append(text);
    }
  m_option->m_filters = list;
}

void KNewProjectDlg::saveBackupExtensionOptions()
{
  TQString backupExt = m_leBackup->text();
  m_option->m_backup = (m_chbBackup->isChecked() && !backupExt.isEmpty());
  m_option->m_backupExtension = backupExt;
}

void KNewProjectDlg::setDatas(const TQString& directoryString, const TQString& filterString)
{
  if (!directoryString.isEmpty())
    m_cbLocation->setEditText(directoryString);

  if (!filterString.isEmpty())
    m_cbFilter->setEditText(filterString);
}

bool KNewProjectDlg::contains(TQListView* lv,const TQString& s, int column)
{
  TQListViewItem* i = lv->firstChild();
  while (i != 0)
    {
      if(i->text(column) == s)
        return true;
      i = i->nextSibling();
    }
  return false;
}

void KNewProjectDlg::whatsThis()
{
  TQWhatsThis::add(m_cbLocation, cbLocationWhatthis);
  TQWhatsThis::add(m_cbFilter, cbFilterWhatthis);

  TQWhatsThis::add(m_chbSizeMin, edSizeMinWhatthis);
  TQWhatsThis::add(m_spbSizeMin, edSizeMinWhatthis);
  TQWhatsThis::add(m_chbSizeMax, edSizeMaxWhatthis);
  TQWhatsThis::add(m_spbSizeMax, edSizeMaxWhatthis);
  TQWhatsThis::add(m_chbLimitDepth, edMaxDepthWhatthis);
  TQWhatsThis::add(m_spbMaxDepth, edMaxDepthWhatthis);

  TQWhatsThis::add(m_cbDateValid, cbDateValidWhatthis);
  TQWhatsThis::add(m_chbDateMin, chbDateMinWhatthis);
  TQWhatsThis::add(m_chbDateMax, chbDateMaxWhatthis);

  TQWhatsThis::add(m_chbIncludeSubfolders, chbRecursiveWhatthis);
  TQWhatsThis::add(m_chbRegularExpressions, chbRegularExpressionsWhatthis);
  TQWhatsThis::add(m_chbEnableVariables, chbVariablesWhatthis);
  TQWhatsThis::add(m_chbCaseSensitive, chbCaseSensitiveWhatthis);
  TQWhatsThis::add(m_chbBackup, chbBackupWhatthis);
  TQWhatsThis::add(m_leBackup, chbBackupWhatthis);
  TQWhatsThis::add(m_cbSearch, leSearchWhatthis);
  TQWhatsThis::add(m_cbReplace, leReplaceWhatthis);
}

#include "knewprojectdlg.moc"