/***************************************************************************
 * $Id: trayicon.cpp,v 1.10 2008/07/31 19:56:28 hoganrobert Exp $
 *   Copyright (C) 2006 - 2008 Robert Hogan                                *
 *   robert@roberthogan.net                                                *
 *                                                                         *
 *   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 St, Fifth Floor, Boston, MA 02110-1301, USA.              *
 ***************************************************************************
 * This is a modified version of trayicon.cpp from ktorrent.               *
 * Original copyright notice follows:                                      *
 ***************************************************************************
 *   Copyright (C) 2005 by                                                 *
 *   Joris Guisson <joris.guisson@gmail.com>                               *
 *   Ivan Vasic <ivasic@gmail.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.                                   *
 *                                                                         *
 *   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 Street, Fifth Floor, Boston, MA 02110-1301, USA.             *
 ***************************************************************************/

#include <tqtooltip.h>
#include <tqstringlist.h>

#include <tdepopupmenu.h>
#include <kurldrag.h>
#include <kdebug.h>
#include <tdelocale.h>
#include <tdeapplication.h>
#include <kpassivepopup.h>

#include "trayicon.h"
#include "trayhoverpopup.h"
#include "torkconfig.h"


TrayIcon::TrayIcon( tork *parent, const char *name)
		: KSystemTray(parent, name)
{
	m_kt_pix = loadIcon("tork");
	setPixmap(m_kt_pix);
	paint=new TQPainter( this );
	drawContents ( paint );
	m_parent = parent;

    setAcceptDrops( true );
	m_hover_popup = new TrayHoverPopup(m_kt_pix,this);

	connect(this,TQ_SIGNAL(quitSelected()),kapp,TQ_SLOT(quit()));
	
	connect(this->contextMenu(),TQ_SIGNAL(aboutToShow()),m_hover_popup,TQ_SLOT(contextMenuAboutToShow()));
	connect(this->contextMenu(),TQ_SIGNAL(aboutToHide()),m_hover_popup,TQ_SLOT(contextMenuAboutToHide()));
}

TrayIcon::~TrayIcon()
{}

void  TrayIcon::dragEnterEvent(TQDragEnterEvent *e)
{
    e->accept (KURLDrag::canDecode(e));
}

void  TrayIcon::dropEvent (TQDropEvent *o)
{
    KURL::List list;
    TQString text;
    if ( KURLDrag::decode( o, list ) )
            droppedfile(list);
}

void  TrayIcon::droppedfile (KURL::List url)
{
    m_parent->startEverything();
    if (TorkConfig::availablePrograms().contains("konqueror"))
      m_parent->enableTDEAndLaunchKonqWithUrl(url.first().url());
    else if (TorkConfig::availablePrograms().contains("firefox"))
      m_parent->anonymizedFirefox(url.first().url());
}


void TrayIcon::enterEvent(TQEvent* ev)
{
	KSystemTray::enterEvent(ev);
	m_hover_popup->enterEvent();
}

void TrayIcon::leaveEvent(TQEvent* )
{
	m_hover_popup->leaveEvent();
}

void TrayIcon::updateStats(const TQString & downloadBandwidthHist, 
                           const TQString & uploadBandwidthHist,
                           const TQString & downloadBandwidth, const TQString & uploadBandwidth,
                           const TQStringList & serverReport, const TQStringList & clientReport,
                           const TQString & curBandwidthRate)
{

    TQString serverStatus;
	for ( TQStringList::ConstIterator it = serverReport.begin(); it != serverReport.end(); ++it )
	{
		if ((*it).isEmpty())
			continue;
        if ((it) != serverReport.begin())
            serverStatus.append(TQString("<tr><td></td><td colspan='2'>%1</td></tr>").arg((*it)));
    }

	TQString tip = i18n("<table cellpadding='2' cellspacing='2'align='center'>"
                        "<tr>"
                          "<td><b>Client:</b></td>"
                          "<td colspan='2'>%1</td>"
                        "</tr>")
                        .arg(*clientReport.begin());
    if (!TorkConfig::clientOnly()){
        tip.append(i18n("<tr>"
                          "<td><b>Server:</b></td>"
                          "<td colspan='2'>Nickname <b>%1</b></td>"
                        "</tr>"
                        "<tr>"
                          "<td></td>"
                          "<td colspan='2'>%2</td>"
                        "</tr>"
                        "%3")
                        .arg(TorkConfig::nickName())
                        .arg(*serverReport.begin())
                        .arg(serverStatus));
    }
    tip.append(i18n(    
                        "<tr>"
                          "<td></td>"
                          "<td><b>BW Down</b></td>"
                          "<td><b>BW Up</b></td>"
                        "</tr>"
                        "<tr>"
                          "<td><b>Speed:</b></td>"
                          "<td><font color='#1c9a1c'>%1</font></td>"
                          "<td><font color='#990000'>%2</font></td>"
                        "</tr>"
                        "<tr>"
                          "<td><b>Total:</b></td>"
                          "<td><font color='#1c9a1c'>%3</font></td>"
                          "<td> <font color='#990000'>%4</font></td>"
                        "</tr>"
                        "<tr>"
                          "<td><b>Max:</b></td>"
                          "<td><font color='#1c9a1c'>%5</font></td>"
                          "<td> <font color='#990000'>%6</font></td>"
                        "</tr>"
                        "</table>")
                        .arg(downloadBandwidth)
                        .arg(uploadBandwidth)
                        .arg(downloadBandwidthHist)
                        .arg(uploadBandwidthHist)
                        .arg(curBandwidthRate)
                        .arg(curBandwidthRate));

	m_hover_popup->updateText(tip);
	
}

SetMaxRate::SetMaxRate( tork *parent, const char *name):TDEPopupMenu(parent, name)
{
    m_parent = parent;
    m_rate = TorkConfig::bandwidthRate();
	makeMenu();
	connect(this,TQ_SIGNAL(activated(int)),this,TQ_SLOT(rateSelected(int)));
}
void SetMaxRate::makeMenu()
{

	int maxBandwidth=(m_rate > 0) ? m_rate : 300 ;
	int delta = 0;
	int maxBandwidthRounded;

	setCheckable(true);
	insertTitle(i18n("Bandwidth Limit"));

	if((maxBandwidth%5)>=3)
		maxBandwidthRounded=maxBandwidth + 5 - (maxBandwidth%5);
	else
		maxBandwidthRounded=maxBandwidth - (maxBandwidth%5);

	for (int i = 0; i < 15; i++)
	{
		TQValueList<int> valuePair;
		if (delta == 0)
			valuePair.append(maxBandwidth);
		else
		{
			if((maxBandwidth%5)!=0)
			{
				valuePair.append(maxBandwidthRounded - delta);
				valuePair.append(maxBandwidthRounded + delta);
			}
			else
			{
				valuePair.append(maxBandwidth - delta);
				valuePair.append(maxBandwidth + delta);
			}
		}

		for (int j = 0; j < (int)valuePair.count(); j++)
		{
			if (valuePair[j] >= 1)
			{
				if(m_rate == valuePair[j] && j==0)
				{
					setItemChecked(insertItem(TQString("%1 KB/s").arg(valuePair[j]),-1, (j == 0) ? 2 : (int)count()), true);
				}
				else
					insertItem(TQString("%1 KB/s").arg(valuePair[j]),-1, (j == 0) ? 2 : (int)count());
			}
		}

		delta += (delta >= 50) ? 50 : (delta >= 20) ? 10 : 5;

	}
}
void SetMaxRate::update()
{
	clear();
	makeMenu();
}

void SetMaxRate::rateSelected(int id)
{

//     kdDebug() << id << endl;
//     kdDebug() << text(id) << endl;
//     kdDebug() << text(id).toInt() << endl;

    //TQt Bug: The value referenced by the TQPopUpMenu ID often has an ampersand
    TQString textID = text(id);
    textID.replace("&","");
    textID.replace(" KB/s","");

//     kdDebug() << textID << endl;
//     kdDebug() << textID.toInt() << endl;

    m_rate=textID.toInt();
	m_parent->setBandwidthFromSysTray(m_rate);
	TorkConfig::setBandwidthRate(m_rate);
	TorkConfig::setBandwidthBurst(m_rate*2);
	TorkConfig::writeConfig();

	update();
}


#include "trayicon.moc"
