/***************************************************************************
 *   Copyright (C) 2004 by Judd Baileys                                    *
 *   jbaileys@bigpond.net.au                                               *
 *                                                                         *
 *   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.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include <kwin.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kpopupmenu.h>
#include <kmessagebox.h>
#include <qclipboard.h>
#include <klocale.h>
#include <kstdaction.h>
#include "configuration.h"
#include <qtooltip.h>
#include "docking.h"
#include "pppstats.h"
#include "kdsl.h"
#include <kwin.h>
#include <kaboutdata.h>
#include "aboutdlg.h"
#include "docbrowser.h"
#include <qpoint.h>
#include <kdebug.h>
#include <khtmlview.h>
#include <khtml_part.h>
#include "notify.h"
#define Icon(x) KGlobal::instance()->iconLoader()->loadIcon(x, KIcon::Toolbar)

 extern DockWidget *dock_widget;
 extern kdsl *m_kdsl;
 DockWidget *DockWidget::dock_widget = 0;
 extern DocBrowser *browser;
 extern kdslStats *kdsl_stats;

DockWidget::DockWidget(QWidget *parent, const char *name, PPPStats *st)
  : KSystemTray(parent, name), stats(st)

{

	KActionCollection* actionCollection = new KActionCollection(this);

	ipFound=false;

	QString themedir;
	if(gpppdata.defaultTheme().isEmpty()) {
	themedir = "kdsl";
	gpppdata.setThemename("kdsl");
	gpppdata.save();	
	}
	else {
	themedir = gpppdata.defaultTheme();
	}
	QString both = themedir + "/dock_both";
	QString left = themedir + "/dock_left";
	QString right = themedir + "/dock_right";
	QString none = themedir + "/dock_none";
	QString discon = themedir + "/dock_discon";

        dock_none_pixmap = UserIcon(none);
        dock_left_pixmap = UserIcon(left);
        dock_right_pixmap = UserIcon(right);
        dock_both_pixmap = UserIcon(both);
	dock_discon_pixmap = UserIcon(discon);

	KAction* about = KStdAction::aboutApp(this, SLOT (showAbout()), actionCollection);
	conToProv = new KAction(i18n("Connect"), Icon("connect_creating"), 0, 0, 0, actionCollection, 0);
	disFromProv = new KAction(i18n("Disconnect"), Icon("connect_no"), 0, 0, 0, actionCollection, 0);
	setupWin = new KAction(i18n("Setup and Configuration"), Icon("configure"),0 ,0 ,0, actionCollection, 0);
	KAction* status = new KAction(i18n("Show Statistics"), Icon("identity"), 0, 0, 0, actionCollection, 0);
	docbrows = new KAction(i18n("Help and Documentation"), Icon("contents"), 0, 0, 0, actionCollection, 0);

        connect (docbrows, SIGNAL(activated()), this, SLOT(browsDoc()));
	connect (disFromProv, SIGNAL(activated()), this, SLOT(discon()));
	connect (status, SIGNAL(activated()), this, SLOT(getStatus()));
	connect (stats, SIGNAL(statsChanged(int)), SLOT(paintIcon(int)));
	connect(conToProv, SIGNAL(activated()), this, SLOT(con()));
	connect(setupWin, SIGNAL(activated()), this, SLOT(setupConfig()));
	connect(this, SIGNAL(quitSelected()), this, SLOT (quitSelected()));

	contextMenu()->clear();
	contextMenu()->insertTitle(Icon("kdsl"), i18n("KDE Broadband"), 0);
	conToProv->plug(contextMenu(), 1);
	disFromProv->plug(contextMenu(), 2);
	contextMenu()->insertSeparator(3);
	setupWin->plug(contextMenu(),4);
	status->plug(contextMenu(), 5);
	contextMenu()->insertSeparator(6);
	about->plug(contextMenu(), 7);
	docbrows->plug(contextMenu(), 8);

	 useMeter = new KAction(i18n("Your Usage Meter"), Icon("find"), 0, 0, 0, actionCollection, 0);
	 useMeter->plug(contextMenu(), 7);
	 connect (useMeter, SIGNAL(activated()), this, SLOT(usageMeter()));
	 
	if(!gpppdata.storeUsage()) {
	useMeter->setEnabled(FALSE);	 
	 }
    				 balloon_timer = new QTimer(this);
    				  connect(balloon_timer, SIGNAL(timeout()),this, SLOT(hideBalloon()));    
       checkStats = new QTimer(this);       
      connect(checkStats, SIGNAL(timeout()),this, SLOT(statsRestart())); 				
     kdsl_stats = new kdslStats(0L, "statsw", 0, stats);
     kdsl_stats->take_stats();

//      kdsl_stats->timeLabel->setText("0:00:00");		  
}

DockWidget::~DockWidget(){
        DockWidget::dock_widget = 0;
}

void DockWidget::quitSelected()
{
     emit setWidgets();
     emit iconDisconnect();
     m_kdsl->shutDown();
 }
 
void DockWidget::setupConfig()
{
	emit configSetup();
}

void DockWidget::addBalloon()
{
	m_balloon = new KopeteBalloon(
				i18n( "<qt><br><center>Connected To</center><b><center> %1</center></b></br></qt>" )
					.arg( gpppdata.accname() ));
				m_balloon->setAnchor(mapToGlobal(QPoint(0,0)));
				m_balloon->show();
				KWin::setOnAllDesktops(m_balloon->winId(), true);

				  balloon_timer->start(3000);	// Notify Window is up for 3 seconds
				  
}

void DockWidget::hideBalloon()
{
	m_balloon->hide();
}
     
/** The entire point of the kdsl browser philosophy is we want something that simply does the job with little frills (we dont want or need a full blown browser)
    The browser was implemented originally for the Help and Documentation section, and here we're extending it for a new use of finding externally our
    Usage data.  In some cases, (with Telstra's Usage protocol in Australia), our 'lil browser will not do the job - therefore we implement support to use an 
    external browser if its necessary.  This way, we dont have to do hundreds of lines of code just to implement features that are necessary for a minority of
    users. 
*/     

void DockWidget::usageMeter()
    {
    if(gpppdata.storeBrowserUsage()==0) {  // We are going to use the Inline Browser, and pop it up.
	browser = new DocBrowser();
	browser->resize(600,600);
	browser->setCaption("kdsl - Usage Meter");
	browser->show();
	browser->khtmlpart->setMetaRefreshEnabled(true);
        KURL url = gpppdata.usageURL();	
        browser->khtmlpart->begin();
        browser-> khtmlpart->openURL(url); 
        browser->khtmlpart->end();
     }
     else   // We are going to call on an external Browser
     {
     QString whichBrowser;
     whichBrowser=gpppdata.browserURL();
     QString whichURL;
     whichURL = gpppdata.usageURL();
     
     KProcess *externalBrowser = new KProcess();         // start a new Process called externalBrowser
     *externalBrowser << whichBrowser << whichURL;    // The parameters to pass to the Process....  which are a. The Browser executable 2.  The file we want to call
     
     externalBrowser->start(KProcess::DontCare);  // Lets start the Process
    externalBrowser->detach();  //  We detach the process so we can explicitly kill the process to free up memory.  Otherwise nothing will happen.
     externalBrowser->kill(SIGTERM);  // Killing the process externalBrowser.  This is important so we free up memory, and dont have background processes running.

     }
}
/** Connect */
void DockWidget::con(){
	emit iconConnect();
	conToProv->setEnabled(FALSE);
	disFromProv->setEnabled(TRUE);	
	kdsl_stats->take_stats();
}
/** Disconnect */
void DockWidget::discon(){

//	m_kdsl->start->kill();
	QWidget *pw = parentWidget();
        pw->show();
	disFromProv->setEnabled(FALSE);
	conToProv->setEnabled(TRUE);	
	emit iconDisconnect();
//	kdsl_stats->interfaceDown();
	kdsl_stats->stop_stats();
}
/** Display the IP */

void DockWidget::browsDoc() 
{
  kapp->invokeHelp();
}

void DockWidget::receiveIP(){

	QWidget *pw = parentWidget();
        pw->show();
	emit iconDisconnect();
}

/** Try to get the IP */
void DockWidget::getStatus(){
 //     KMessageBox::information(this, i18n("<qt><center><b><em><h2>Connected to %5</h2></em></b><br>Your local IP address %1<br>Remote IP address %2<br>%3<br>%4</center></qt>"  ).arg(stats->local_ip_address).arg(stats->remote_ip_address).arg(stats->istatus).arg(stats->ostatus).arg(gpppdata.accname()));
     
      kdsl_stats->show();
//      kdsl_stats->paintGraph();
//      kdsl_stats->take_stats();
       checkStats->start(100); //Change Stats Every Second
 }
 
 void DockWidget::statusSetup()
 {
 	kdsl_stats->localIPLabel->show();
        kdsl_stats->remoteIPLabel->show();
        kdsl_stats->connectionLabel->show();
	kdsl_stats->take_stats();	
}
 
 void DockWidget::clock(QString clock) {
//      kdsl_stats->updateGraph();
       kdsl_stats->timeLabel->setText(clock);      
       }
       
 void DockWidget::statsRestart() {
 //      kdsl_stats->connectionLabel->show();
 //      kdsl_stats->localIPLabel->show();
//       kdsl_stats->remoteIPLabel->show();
 //      kdsl_stats->connectionLabel->setText(gpppdata.accname());
 //     kdsl_stats->timeLabel->setText(m_kdsl->time_string2);
      kdsl_stats->localIPLabel->setText(stats->local_ip_address);
      kdsl_stats->remoteIPLabel->setText(stats->remote_ip_address);
       kdsl_stats->receivedLabel->setText(stats->istatus);
       kdsl_stats->sentLabel->setText(stats->ostatus);

       
        checkStats->start(100);
//	getStatus();
}
/** Executes the about-dialog. */
void DockWidget::showAbout(){

        AboutDialog* aboutdlg = new AboutDialog;
	aboutdlg->resize(500,300);
//        about->setLogo(UserIcon ("kppp2") );

//	about->setAuthor( "Authored by Judd Baileys", "jbaileys@bigpond.net.au", "http://kdslbroadband.sourceforge.net", "\n\nKdsl, a frontend to pppd for xDSL connections.\n\nLicensed under the GPL General Public License\n\nA special thank-you to Diego Levrero for\nhis enhancements and Italian translations to kdsl\n" );
//        about->setVersion("Kdsl 0.4\n Broadband for KDE");
//	about->addContributor("Diego Levrero for his enhancements","","","");
        aboutdlg->show();
}
/** Called when start terminates */
void DockWidget::connected(void){

}
/** Called when stop terminates */
void DockWidget::disconnected(void){
}

void DockWidget::paintEvent (QPaintEvent *) {
   if(this->conToProv->isEnabled()) {
   paintIcon(PPPStats::BytesNone);   
  paintIcon(PPPStats::BytesDiscon);
  }
  else
   paintIcon(PPPStats::BytesNone); 
}

void DockWidget::paintIcon (int status)
{
const QPixmap *pixmap;
	QString themedir;
	themedir = gpppdata.defaultTheme();
	QString both = themedir + "/dock_both";
	QString left = themedir + "/dock_left";
	QString right = themedir + "/dock_right";
	QString none = themedir + "/dock_none";
	QString discon =  "kdsl/dock_discon";

      dock_none_pixmap = UserIcon(none);
      dock_left_pixmap = UserIcon(left);
      dock_right_pixmap = UserIcon(right);
      dock_both_pixmap = UserIcon(both);
      dock_discon_pixmap = UserIcon(discon);

    switch(status)
      {

      case PPPStats::BytesBoth:
        pixmap = &dock_both_pixmap;
        break;
      case PPPStats::BytesIn:
        pixmap = &dock_left_pixmap;

        break;
      case PPPStats::BytesOut:
        pixmap = &dock_right_pixmap;
	
        break;
      case PPPStats::BytesNone:
  
        pixmap = &dock_none_pixmap;
        break;
	
      case PPPStats::BytesDiscon:
        default:   
        pixmap = &dock_discon_pixmap;
        break;  

      }

    bitBlt(this, 0, 0, pixmap);

    }

void DockWidget::refreshIcon()
{
update();
}

void DockWidget::take_stats() {
	QWidget *pw = parentWidget();
        pw->hide();
}

void DockWidget::stop_stats() {
  stats->stop();
  kdsl_stats->stop_stats();
}

#include "docking.moc"

