#include <math.h>
#include <stdlib.h>

#include <config.h>
#ifdef HAVE_SYS_LOADAVG_H
#include <sys/loadavg.h> // e.g. Solaris
#endif

#include <tqpainter.h>
#include <tqbitmap.h>
#include <tqdatetime.h>
#include <tqdrawutil.h>
#include <tqtimer.h>

#include <kdebug.h>
#include <tdeglobal.h>
#include <twin.h>
#include <kiconloader.h>
#include <kpixmap.h>
#include <kpixmapeffect.h>
#include <tdelocale.h>
#include <kstandarddirs.h>
#include <tdepopupmenu.h>

#include <taskmanager.h>

#include "kaspopup.h"
#include "kastasker.h"

#include "kasloaditem.h"
#include "kasloaditem.moc"

KasLoadItem::KasLoadItem( KasBar *parent )
    : KasItem( parent )
{
    TQTimer *t = new TQTimer( this, "KasLoadItem::t" );
    connect( t, TQT_SIGNAL( timeout() ), TQT_SLOT( updateDisplay() ) );
    t->start( 1000 );
    updateDisplay();

    connect( this, TQT_SIGNAL(rightButtonClicked(TQMouseEvent *)), TQT_SLOT(showMenuAt(TQMouseEvent *) ) );
}

KasLoadItem::~KasLoadItem()
{
}

void KasLoadItem::updateDisplay()
{
  double load[3];
  
  int ret = getloadavg( load, 3 );
  if ( ret == -1 )
    return;

  valuesOne.append( load[0] );
  valuesFive.append( load[1] );
  valuesFifteen.append( load[2] );

  if ( valuesOne.count() > 2/*(extent()-2)*/ ) {
    valuesOne.pop_front();
    valuesFive.pop_front();
    valuesFifteen.pop_front();
  }

  setText( TQString("%1").arg( valuesOne.last(), 3, 'f', 2 ) );
}

void KasLoadItem::paint( TQPainter *p )
{
    double val = valuesOne.last();
    double maxValue = 1.0;
    double scaleVal = TQMAX( val, valuesFive.last() );

    if ( scaleVal >= maxValue )
	maxValue = 2.0;
    if ( scaleVal >= maxValue )
	maxValue = 5.0;
    if ( scaleVal >= maxValue )
	maxValue = 10.0;
    if ( scaleVal >= maxValue )
	maxValue = 20.0;
    if ( scaleVal >= maxValue )
	maxValue = 50.0;
    if ( scaleVal >= maxValue )
	maxValue = 100.0;

    double dh = extent()-16;
    dh = dh / maxValue;

    int h = (int) floor( dh * val );
    int w = extent()-4;
    h = (h > 0) ? h : 1;
    w = (w > 0) ? w : 1;

    KasItem::paint( p );

    TQColor light = kasbar()->colorGroup().highlight();
    TQColor dark = light.dark();

    KPixmap pix;
    pix.resize( w, h );
    KPixmapEffect::gradient( pix, light, dark, KPixmapEffect::DiagonalGradient );
    p->drawPixmap( 2, extent()-2-h, pix );

    p->setPen( kasbar()->colorGroup().mid() );
    for ( double pos = 0.2 ; pos < 1.0 ; pos += 0.2 ) {
	int ypos = (int) floor((extent()-2) - (dh*maxValue*pos));
	p->drawLine( 2, ypos, extent()-3, ypos );
    }
}

void KasLoadItem::showMenuAt( TQMouseEvent *ev )
{
    hidePopup();
    showMenuAt( ev->globalPos() );
}

void KasLoadItem::showMenuAt( TQPoint p )
{
    mouseLeave();
    kasbar()->updateMouseOver();

    KasTasker *bar = dynamic_cast<KasTasker *> (KasItem::kasbar());
    if ( !bar )
	return;

    TDEPopupMenu *menu = bar->contextMenu();
    menu->exec( p );
}