/***************************************************************************
 *   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/QMenu>
#include <QtCore/QTextStream>

#include <KApplication>
#include <KToggleAction>
#include <KMenu>
#include <KAction>
#include <KLocale>
#include <KActionCollection>
#include <KStandardAction>
#include <KStatusBar>
#include <KFileDialog>
#include <KMessageBox>
#include <KIO/NetAccess>
#include <KSaveFile>
#include <KSystemTrayIcon>
#include <KIcon>

#include <KDebug>

#include "PacketListView.h"
#include "CaptureDialog.h"
#include "options/OptionDialog.h"
#include "options/KSConfig.h"
#include "mainwindow.h"


MainWindow::MainWindow(QWidget *parent)
    : KXmlGuiWindow(parent),
      m_fileName(QString())
{
  m_packetListView = new PacketListView;
  setCentralWidget(m_packetListView);

  m_tray = new KSystemTrayIcon(this);
  m_tray->setIcon(KIcon("ksniffer"));
/*  if (Settings::showSystemTrayIcon())
                {
                        tray_icon->updateMaxRateMenus();
                        tray_icon->show();
                }
                else
                        tray_icon->hide();
 */

  setupActions();
  setupTray();

  // reset main widget title
  setPlainCaption( i18n("KSniffer - A KDE Network Sniffer") );

  // no captured-packets available yet
  m_needToSavePackets = false;
}


void MainWindow::setupActions()
{
  // the action New Capture
  m_actNew = KStandardAction::openNew( this, SLOT(slotNewCapture()), actionCollection() );
  m_actNew->setText(i18n("New..."));
  m_actNew->setIcon(KIcon("document-new"));
  m_actNew->setShortcut(Qt::CTRL + Qt::Key_N);
  m_actNew->setWhatsThis( i18n( "<b>New Capture</b><br>Start a new packet-capture session." ) );
  m_actNew->setToolTip( i18n( "start a new packet-capture session" ) );
  actionCollection()->addAction("capt_new", m_actNew);

  // the action Open Captured-Packet File
  m_actOpen = KStandardAction::open( this, SLOT(slotOpen()), actionCollection() );
  m_actOpen->setWhatsThis( i18n("<b>Open</b><br>Open a previous packet-capture session file.") );
  m_actOpen->setToolTip( i18n( "open a previous packet-capture session file" ) );
  actionCollection()->addAction("capt_open", m_actOpen);

  // the action Open Recent Captured-Packet File
  //m_actOpenRecent = KStdAction::openRecent(this, SLOT(slotOpen(const KURL&)), actionCollection(), "capt_open_recent" );

  // the action Save Captured-Packet File
  m_actSave = KStandardAction::save( this, SLOT(slotSave()), actionCollection() );
  m_actSave->setWhatsThis( i18n( "<b>Save</b><br>Save the current packet-capture session." ) );
  m_actSave->setToolTip( i18n( "save the current packet-capture session" ) );
  m_actSave->setEnabled( false );
  actionCollection()->addAction("capt_save", m_actSave);

  // the action Save Captured-Packet File As
  m_actSaveAs = KStandardAction::saveAs( this, SLOT(slotSaveAs()), actionCollection() );
  m_actSaveAs->setWhatsThis( i18n( "<b>Save As...</b><br>Save into a file the current packet-capture session." ) );
  m_actSaveAs->setToolTip( i18n( "save the current packet-capture session as" ) );
  m_actSaveAs->setEnabled( false );
  actionCollection()->addAction("capt_save_as", m_actSaveAs);

  // the action Pause/Continue Capture
  m_actPauseContinue =  new KAction(this);
  m_actPauseContinue->setText(i18n("&Pause"));
  m_actPauseContinue->setIcon(KIcon("media-playback-pause"));
  m_actPauseContinue->setShortcut(Qt::CTRL + Qt::Key_P);
  m_actPauseContinue->setToolTip( i18n( "pause the current packet-capture session" ) );
  
  m_whatsthisPause = i18n("<b>Pause Capture</b><br>Pause the packet-capture. With "\
      "this command you will not capture any packet till you don't decide to continue to capture them "\
      "again.");
  m_actPauseContinue->setWhatsThis( m_whatsthisPause );
  m_actPauseContinue->setEnabled( false );
  actionCollection()->addAction("capt_pause_continue", m_actPauseContinue);
  connect(m_actPauseContinue, SIGNAL(triggered(bool)), this, SLOT(slotPauseContinue()));

  // the action Stop Capture
  m_actStop = new KAction(this);
  m_actStop->setText(i18n("S&top"));
  m_actStop->setIcon(KIcon("media-playback-stop"));
  m_actStop->setShortcut(Qt::CTRL + Qt::Key_End);
  m_actStop->setWhatsThis( i18n("<b>Stop</b><br>Stop the packet-capture session.") );
  m_actStop->setToolTip( i18n( "stop the current packet-capture session" ) );
  m_actStop->setEnabled( false );
  actionCollection()->addAction("capt_stop", m_actStop);
  connect(m_actStop, SIGNAL(triggered(bool)), this, SLOT(slotStop()));


  // the action Print Captured-Packet
/*  m_actPrint = KStdAction::print(this, SLOT(slotPrint()), actionCollection(), "capt_print");
  m_actPrint->setWhatsThis( i18n("<b>Print...</b><br>Print the packet-capture session.") );
  m_actPrint->setEnabled( false );*/

  // the action Quit
  KStandardAction::quit(kapp, SLOT(quit()),
                        actionCollection());

  KAction *m_actQuit = KStandardAction::quit( this, SLOT(slotQuit()), actionCollection() );
  m_actQuit->setWhatsThis( i18n("<b>Quit</b><br>Stop the packet-capture session and quit from KSniffer.") );
  m_actQuit->setToolTip( i18n( "stop the current packet-capture and quit" ) );
  m_actQuit->setText( i18n("Quit") );
  actionCollection()->addAction("capt_quit", m_actQuit);

  statusBar()->showMessage( i18n("Ready.") );
  /*
  KStandardAction::keyBindings(this, SLOT(optionsConfigureKeys()), actionCollection());
  KStandardAction::configureToolbars(this, SLOT(optionsConfigureToolbars()), actionCollection());
  KStandardAction::preferences(this, SLOT(optionsSettings()), actionCollection());
  */

  // make sure the tooltips are used for the menu
  //actionCollection()->setHighlightingEnabled( true );

  // setup Settings menu
  //m_statusbarAction = KStdAction::showStatusbar( this, SLOT(optionsShowStatusbar()), actionCollection() );

  setupTray();
  setupGUI();
}


void MainWindow::setupTray()
{
  m_tray->contextMenu()->clear();

  // Sub menu: "Capture" item
  KMenu *popupCapture = new KMenu ( this );
  popupCapture->setTitle(i18n("&Capture"));
  popupCapture->setIcon(KIcon("hwinfo"));

  // the subitems...
  popupCapture->addAction( m_actNew );
  popupCapture->addAction( m_actOpen );
  popupCapture->addAction( m_actSave );
  popupCapture->addAction( m_actSaveAs );
  popupCapture->addAction( m_actPauseContinue );
  popupCapture->addAction( m_actStop );
  //popupCapture->addAction( m_actPrint );

  m_tray->contextMenu()->addMenu( popupCapture );

  // Sub menu: "Help" item
  KMenu *popupHelp = helpMenu();
  popupHelp->setIcon(KIcon("ksniffer"));
  //i18n("&Help")
  m_tray->contextMenu()->addMenu( popupHelp );

  // KSniffer settings
  KAction *preferences = KStandardAction::preferences(this, SLOT(slotShowSettings()), actionCollection());
  m_tray->contextMenu()->addSeparator();
  m_tray->contextMenu()->addAction( preferences );

  // show tray if needed
  m_config = KGlobal::config()->group("GUI");
  if ( m_config.readEntry( "Show Tray Bar", false ) )
    m_tray->show();
}


void MainWindow::slotNewCapture()
{
  QString msg = statusBar()->currentMessage();
  statusBar()->showMessage( i18n("New Capture: select the network interface to start sniffing packets.") );
  CaptureDialog cd(m_tray);
  if (cd.exec())
  {
    QString currentInterfaceText = KSConfig::sniffingInterface();

    // show tray bar if needed (the options could be changed)
    if ( KSConfig::showTrayBar() )
      m_tray->show();
    else
      m_tray->hide();

    // now we can "start"...
/*    if (m_sniffer->packetsAvailable() && m_needToSave)
      if ( KMessageBox::warningContinueCancel( this,
              i18n("<p>Packet-capture session data available. If you want to start a " \
                   "new capture session you are going to lose all captured data.</p>" \
                   "<p>Do you really want to continue?</p>" ) ) == KMessageBox::Cancel )
        return;
      else
      {
        // need to save data when available
        m_needToSavePackets = true;

        // we have to remove the captured data
        m_packets->clearList();
      }
    else
    {
      // need to save data when available
      m_needToSavePackets = true;
    }
    statusBar()->showMessage( i18n("Sniffing network by \"%1\" interface.").arg(cod->selectedInterface()) );

    m_wroteTmpLocalFile = true;
    startLiveSniffing( cod->selectedInterface() );
  }
  else
    statusBar()->showMessage( msg );
  */
  }
}


void MainWindow::slotOpen( const KUrl& urlParam )
{
  Q_UNUSED( urlParam );
}


void MainWindow::slotSave()
{
}


void MainWindow::slotSaveAs()
{
}


//void slotPrint(){}

void MainWindow::slotPauseContinue()
{
}


void MainWindow::slotStop()
{
}


void MainWindow::slotQuit()
{
}


void MainWindow::slotShowSettings()
{
  OptionDialog optD(m_tray);
  optD.exec();
}


//void MainWindow::saveFileAs(const QString &outputFileName)
//{
  /*
  KSaveFile file(outputFileName);
  file.open();
 
  QByteArray outputByteArray;
  outputByteArray.append(textArea->toPlainText());
  file.write(outputByteArray);
  file.finalize();
  file.close();
 */
//  m_fileName = outputFileName;
//}


/*void MainWindow::saveFileAs()
{
  //saveFileAs(KFileDialog::getSaveFileName());
}


void MainWindow::saveFile()
{
  if(!m_fileName.isEmpty())
  {
    saveFileAs(m_fileName);
  }
  else
  {
    saveFileAs();
  }
}


void MainWindow::openFile()
{
  openFile(KFileDialog::getOpenFileName());
}
*/

void MainWindow::openFile(const QString &inputFileName)
{
  QString tmpFile;
  if(KIO::NetAccess::download(inputFileName, tmpFile, 
         this))
  {
/*    QFile file(tmpFile);
    file.open(QIODevice::ReadOnly);
    textArea->setPlainText(QTextStream(&file).readAll());
    m_fileName = inputFileName;
 
    KIO::NetAccess::removeTempFile(tmpFile);
    */
  }
  else
  {
    KMessageBox::error(this, 
        KIO::NetAccess::lastErrorString());
  }
}
