/***************************************************************************
 *   Copyright (C) 2004-2010 by Giovanni Venturi                           *
 *   giovanni@ksniffer.org                                                 *
 *                                                                         *
 *   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 Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *
 ***************************************************************************/

#include <QtGui/QCheckBox>
#include <QtGui/QRadioButton>
#include <QtGui/QSpinBox>
#include <QtGui/QComboBox>
#include <QtGui/QToolTip>
#include <QtGui/QWhatsThis>

#include <KUrlRequester>
#include <KUniqueApplication>
#include <KConfig>
#include <KMessageBox>
#include <KStandardDirs>
#include <KLocale>

#include "SnifferOptionTab.h"
//#include "CaptureOption.h"

SnifferOptionTab::SnifferOptionTab(QWidget *parent)
  : QWidget(parent)
{
  QWidget *widget = new QWidget( this );

  // create the user interface, the parent widget is "widget"
  ui.setupUi(widget); // this is the important part
    
  m_stopButtons << ui.m_checkManually;
  m_stopButtons << ui.m_checkPackets;
  m_stopButtons << ui.m_checkSize;
  m_stopButtons << ui.m_checkTime;
  ui.m_editTempDir->setMode( KFile::Directory );

  connect( ui.m_checkPackets, SIGNAL(clicked()), this, SLOT(checkSelectPackets()) );
  connect( ui.m_checkSize, SIGNAL(clicked()), this, SLOT(checkSelectSize()) );
  connect( ui.m_checkTime, SIGNAL(clicked()), this, SLOT(checkSelectTime()) );
  connect( ui.m_checkManually, SIGNAL(clicked()), this, SLOT(checkStopManually()) );

  connect( ui.m_packetsNum, SIGNAL(valueChanged(int)), this, SLOT(checkSelectPackets()) );
  connect( ui.m_packetsSize, SIGNAL(valueChanged(int)), this, SLOT(checkSelectSize()) );
  connect( ui.m_packetsTime, SIGNAL(valueChanged(int)), this, SLOT(checkSelectTime()) );

  ui.m_editTempDir->setToolTip( i18n("The folder where KSniffer stores a temporary file") );
  ui.m_editTempDir->setWhatsThis(
    i18n("<p>This is the default temporary folder where KSniffer will store a temporary "\
         "file for packet-captured session.</p><p>If you want the temporary folder "\
         "can be changed here before starting a new capture session.</p>") );

  ui.m_packetsNum->setToolTip( i18n("Packets number after you want to stop capturing") );
  ui.m_checkPackets->setWhatsThis(
    i18n("<p>If you check this, you can capture just a certain packets number. "\
         "After that number, capture will stop automatically.</p>"\
         "<p>You can active just a kind of \"<b>Stop capture after</b>\". "\
         "For <i>packets number</i>, for <i>packets size</i> or for "\
         "<i>packets time</i>.</p>") );

  ui.m_packetsSize->setToolTip( i18n("Total packets size after you want to stop capturing") );
  ui.m_checkSize->setWhatsThis(
    i18n("<p>If you check this, you can capture just a certain packets number "\
         "for a total maximum packets size. After that size, capture will stop "\
         "automatically.</p>"\
         "<p>You can active just a kind of \"<b>Stop capture after</b>\". "\
         "For <i>packets number</i>, for <i>packets size</i> or for "\
         "<i>packets time</i>.</p>") );

  ui.m_packetsTime->setToolTip( i18n("Packets time after you want to stop capturing") );
  ui.m_checkTime->setWhatsThis(
    i18n("<p>If you check this, you can capture just a certain packets number for a total "\
         "specific maximum time. When you get all packets for a certain time, capture "\
         "will stop automatically.</p>"\
         "<p>You can active just a kind of \"<b>Stop capture after</b>\". "\
         "For <i>packets number</i>, for <i>packets size</i> or for "\
         "<i>packets time</i>.</p>") );

  m_config = KGlobal::config()->group("Sniffer");
}


void SnifferOptionTab::checkStopManually()
{
  exclusiveSelectOf( 0 );
}


void SnifferOptionTab::checkSelectPackets()
{
  exclusiveSelectOf( 1 );
}


void SnifferOptionTab::checkSelectSize()
{
  exclusiveSelectOf( 2 );
}


void SnifferOptionTab::checkSelectTime()
{
  exclusiveSelectOf( 3 );
}


void SnifferOptionTab::exclusiveSelectOf( int which )
{
  int size = static_cast<int>( m_stopButtons.count() );

  for ( int i = 0; i < size; i++ )
    if ( i != which )
      m_stopButtons[i]->setChecked( false );
    else
      m_stopButtons[i]->setChecked( true );

  if (which == 0)
    m_stopButtonSelected = "manually";
  else if (which == 1)
    m_stopButtonSelected = "by packets";
  else if (which == 2)
    m_stopButtonSelected = "by size";
  else if (which == 3)
    m_stopButtonSelected = "by time";
}


/*void SnifferOptionTab::getOptions( CaptureOptions *options )
{
  options->setShowAfter( m_config.readEntry( "Show packets after stopped capture" , false ) );
  options->setTmpDir( m_config.readPathEntry( "Temp dir", KGlobal::dirs()->resourceDirs( "tmp" ).first() ) );

  // load stopping capture type: manually, ...
  QString strWhichStopType = m_config.readEntry( "Stopping Type", "manually" );
  options->setSniffingType( strWhichStopType );

  // for Capture After Packets
  options->setPacketsNumber( m_config.readEntry( "packets number", 0 ) );

  // for Capture After Size
  options->setPacketsSize( m_config.readEntry( "size", 0 ) );
  options->setPacketsInfoSizeUnits( m_config.readEntry( "unit", 0 ) );

  // for Capture After Time
  options->setPacketsTime( m_config.readEntry( "time", 0 ) );
  options->setPacketsInfoTimeUnits( m_config.readEntry( "unit", 0 ) );
}*/


void SnifferOptionTab::readSettings()
{
  QString tempdir = m_config.readPathEntry( "Temp dir", KGlobal::dirs()->resourceDirs( "tmp" ).first() );
  ui.m_editTempDir->setUrl( tempdir );

  // load stopping capture type: manually, ...
  // for Capture Type Options
  m_stopButtonSelected = m_config.readEntry( "Stopping Type", "manually" );

  int whichStopType = -1;

  if (m_stopButtonSelected == "manually")
    whichStopType = 0;
  else if (m_stopButtonSelected == "by packets")
    whichStopType = 1;
  else if (m_stopButtonSelected == "by size")
    whichStopType = 2;
  else if (m_stopButtonSelected == "by time")
    whichStopType = 3;

  // for Capture After Packets
  ui.m_packetsNum->setValue( m_config.readEntry( "packets number", 0 ) );

  // for Capture After Size
  ui.m_packetsSize->setValue( m_config.readEntry( "size", 0 ) );
  ui.m_sizeType->setCurrentIndex( m_config.readEntry( "unit", 0 ) );

  // for Capture After Time
  ui.m_packetsTime->setValue( m_config.readEntry( "time", 0 ) );
  ui.m_timeType->setCurrentIndex( m_config.readEntry( "unit", 0 ) );

  exclusiveSelectOf( whichStopType );
}


bool SnifferOptionTab::saveSettings()
{
  QString tempDir;

  // saving temporary directory URL
  if ( ui.m_editTempDir->url().isLocalFile() )
    tempDir = ui.m_editTempDir->url().toLocalFile();
  else
  {
    KMessageBox::error( this, i18n("Cannot save temporary file into a not local file") );
    return false;
  }

  QFileInfo fi( tempDir );

  if( fi.isRelative() )
    fi.setFile( fi.absoluteFilePath() );

  if( !fi.exists() )
  {
    if( KMessageBox::questionYesNo( this, i18n("Folder %1 does not exist. Do you want to create it?").arg(tempDir),
          i18n("Create Folder") ) == KMessageBox::Yes )
    {
      if( !KStandardDirs::makeDir( fi.absoluteFilePath() ) )
      {
        KMessageBox::error( this, i18n("Unable to create folder %1").arg(tempDir) );
        return false;
      }
    }
    else
      // the directory does not exist and the user doesn't want to create it
      return false;
  }

  if( fi.isFile() )
  {
    KMessageBox::information( this, i18n("You specified a file for the temporary folder. "
      "KSniffer will use its base path as the temporary folder."),
      i18n("Warning"), i18n("Don't show again.") );
    fi.setFile( fi.absolutePath() );
  }

  // check for writing permission
  if( !fi.isWritable() )
  {
    KMessageBox::error( this, i18n("You have not permission to write to %1.").arg(fi.absoluteFilePath()) );
    return false;
  }

  ui.m_editTempDir->setUrl( fi.absoluteFilePath() );
  m_config.writePathEntry( "Temp dir", ui.m_editTempDir->url().toLocalFile() );

  // save stopping capture type: manually, ...
  // for Capture Type Options
  m_config.writeEntry( "Stopping Type", m_stopButtonSelected );

  // for Capture After Packets
  m_config.writeEntry( "packets number", ui.m_packetsNum->value() );

  // for Capture After Size
  m_config.writeEntry( "size", ui.m_packetsSize->value() );
  m_config.writeEntry( "unit", ui.m_sizeType->currentIndex() );

  // for Capture After Time
  m_config.writeEntry( "time", ui.m_packetsTime->value() );
  m_config.writeEntry( "unit", ui.m_timeType->currentIndex() );

  return true;
}

#include "SnifferOptionTab.moc"
