/*
    This file is part of KMail.
    Copyright (c) 2007 Till Adam <adam@kde.org>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

    KMail 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

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the TQt library by Trolltech AS, Norway (or with modified versions
    of TQt that use the same license as TQt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    TQt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "filterimporterexporter.h"

#include "kmfilter.h"
#include "kmfilteraction.h"
#include "util.h"

#include <tdeconfig.h>
#include <kdebug.h>
#include <tdefiledialog.h>
#include <kdialogbase.h>
#include <tdelistview.h>
#include <kpushbutton.h>

#include <tqregexp.h>
#include <tqlayout.h>


using namespace KMail;

FilterSelectionDialog::FilterSelectionDialog( TQWidget * parent )
  :KDialogBase( parent, "filterselection", true, i18n("Select Filters"), Ok|Cancel, Ok, true ),
   wasCancelled( false )
{
  TQWidget *w = new TQWidget( this );
  TQVBoxLayout *top = new TQVBoxLayout( w );

  filtersListView = new TDEListView( w );
  top->addWidget( filtersListView );
  setMainWidget(w);
  filtersListView->setSorting( -1 );
  filtersListView->setSelectionMode( TQListView::NoSelection );
  filtersListView->addColumn( i18n("Filters"), 300 );
  filtersListView->setFullWidth( true );
  TQHBoxLayout *buttonLayout = new TQHBoxLayout( this );
  top->addLayout( buttonLayout );
  selectAllButton = new KPushButton( i18n( "Select All" ), w );
  buttonLayout->addWidget( selectAllButton );
  unselectAllButton = new KPushButton( i18n( "Unselect All" ), w );
  buttonLayout->addWidget( unselectAllButton );
  connect( selectAllButton, TQ_SIGNAL( clicked() ), this, TQ_SLOT( slotSelectAllButton() ) );
  connect( unselectAllButton, TQ_SIGNAL( clicked() ), this, TQ_SLOT( slotUnselectAllButton() ) );
  resize( 300, 350 );
}

FilterSelectionDialog::~FilterSelectionDialog()
{
}

void FilterSelectionDialog::slotCancel()
{
  wasCancelled = true;
  KDialogBase::slotCancel();
}

bool FilterSelectionDialog::cancelled()
{
  return wasCancelled;
}

void FilterSelectionDialog::setFilters( const TQValueList<KMFilter*>& filters )
{
  if ( filters.isEmpty() )
  {
    enableButtonOK( false );
    return;
  }
  originalFilters = filters;
  filtersListView->clear();
  TQValueListConstIterator<KMFilter*> it = filters.constEnd();
  while ( it != filters.constBegin() ) {
    --it;
    KMFilter* filter = *it;
    TQCheckListItem* item = new TQCheckListItem( filtersListView, filter->name(), TQCheckListItem::CheckBox );
    item->setOn( true );
  }
}

TQValueList<KMFilter*> FilterSelectionDialog::selectedFilters() const
{
  TQValueList<KMFilter*> filters;
  TQListViewItemIterator it( filtersListView );
  int i = 0;
  while( it.current() ) {
    TQCheckListItem* item = static_cast<TQCheckListItem*>( it.current() );
    if ( item->isOn() )
      filters << originalFilters[i];
    ++i; ++it;
  }
  return filters;
}

void FilterSelectionDialog::slotUnselectAllButton()
{
  TQListViewItemIterator it( filtersListView );
  while( it.current() ) {
    TQCheckListItem* item = static_cast<TQCheckListItem*>( it.current() );
    item->setOn( false );
    ++it;
  }
}

void FilterSelectionDialog::slotSelectAllButton()
{
  TQListViewItemIterator it( filtersListView );
  while( it.current() ) {
    TQCheckListItem* item = static_cast<TQCheckListItem*>( it.current() );
    item->setOn( true );
    ++it;
  }
}

/* static */
TQValueList<KMFilter*> FilterImporterExporter::readFiltersFromConfig( TDEConfig* config, bool bPopFilter )
{
    TDEConfigGroupSaver saver(config, "General");
    int numFilters = 0;
    if (bPopFilter)
      numFilters = config->readNumEntry("popfilters",0);
    else
      numFilters = config->readNumEntry("filters",0);

    TQValueList<KMFilter*> filters;
    for ( int i=0 ; i < numFilters ; ++i ) {
      TQString grpName;
      grpName.sprintf("%s #%d", (bPopFilter ? "PopFilter" : "Filter") , i);
      TDEConfigGroupSaver saver(config, grpName);
      KMFilter * filter = new KMFilter(config, bPopFilter);
      filter->purify();
      if ( filter->isEmpty() ) {
    #ifndef NDEBUG
        kdDebug(5006) << "KMFilter::readConfig: filter\n" << filter->asString()
          << "is empty!" << endl;
    #endif
        delete filter;
      } else
        filters.append(filter);
    }
    return filters;
}

/* static */
void FilterImporterExporter::writeFiltersToConfig( const TQValueList<KMFilter*>& filters, TDEConfig* config, bool bPopFilter )
{
    // first, delete all groups:
    TQStringList filterGroups =
      config->groupList().grep( TQRegExp( bPopFilter ? "PopFilter #\\d+" : "Filter #\\d+" ) );
    for ( TQStringList::Iterator it = filterGroups.begin() ;
          it != filterGroups.end() ; ++it )
      config->deleteGroup( *it );

    int i = 0;
    for ( TQValueListConstIterator<KMFilter*> it = filters.constBegin() ;
          it != filters.constEnd() ; ++it ) {
      if ( !(*it)->isEmpty() ) {
        TQString grpName;
        if ( bPopFilter )
          grpName.sprintf("PopFilter #%d", i);
        else
          grpName.sprintf("Filter #%d", i);
        TDEConfigGroupSaver saver(config, grpName);
        (*it)->writeConfig(config);
        ++i;
      }
    }
    TDEConfigGroupSaver saver(config, "General");
    if (bPopFilter)
      config->writeEntry("popfilters", i);
    else
      config->writeEntry("filters", i);
}


FilterImporterExporter::FilterImporterExporter( TQWidget* parent, bool popFilter )
:mParent( parent), mPopFilter( popFilter )
{
}

FilterImporterExporter::~FilterImporterExporter()
{
}

TQValueList<KMFilter*> FilterImporterExporter::importFilters()
{
    TQString fileName = KFileDialog::getOpenFileName( TQDir::homeDirPath(), TQString(), mParent, i18n("Import Filters") );
    if ( fileName.isEmpty() )
        return TQValueList<KMFilter*>(); // cancel

    { // scoping
        TQFile f( fileName );
        if ( !f.open( IO_ReadOnly ) ) {
            KMessageBox::error( mParent, i18n("The selected file is not readable. Your file access permissions might be insufficient.") );
            return TQValueList<KMFilter*>();
        }
    }

    TDEConfig config( fileName );
    TQValueList<KMFilter*> imported = readFiltersFromConfig( &config, mPopFilter );
    FilterSelectionDialog dlg( mParent );
    dlg.setFilters( imported );
    dlg.exec();
    return dlg.cancelled() ? TQValueList<KMFilter*>() : dlg.selectedFilters();
}

void FilterImporterExporter::exportFilters(const TQValueList<KMFilter*> & filters )
{
    KURL saveUrl = KFileDialog::getSaveURL( TQDir::homeDirPath(), TQString(), mParent, i18n("Export Filters") );

    if ( saveUrl.isEmpty() || !Util::checkOverwrite( saveUrl, mParent ) )
      return;

    TDEConfig config( saveUrl.path() );
    FilterSelectionDialog dlg( mParent );
    dlg.setFilters( filters );
    dlg.exec();
    if ( !dlg.cancelled() )
        writeFiltersToConfig( dlg.selectedFilters(), &config, mPopFilter );
}

#include "filterimporterexporter.moc"