#include "loadlight.h"
#include <QPainter>

PlasmaLoadLight::PlasmaLoadLight( QObject *parent, 
                                  const QVariantList &args ) 
    : Plasma::Applet( parent, args )
    , m_load( 0.75 )
{
 setBackgroundHints( DefaultBackground );
 resize( 100, 100 );
}

void PlasmaLoadLight::init()
{
 connect( dataEngine( "systemmonitor" ), SIGNAL(sourceAdded(QString)), 
          this, SLOT(sourceAdded(QString)) );
}

void PlasmaLoadLight::sourceAdded( const QString &name )
{
 if( name == "cpu/system/loadavg1" )
 {
   dataEngine( "systemmonitor" )->connectSource( name, this, 1000 );
   disconnect( dataEngine( "systemmonitor" ), SIGNAL(sourceAdded(QString)), 
               this, SLOT(sourceAdded(QString)) );
  }
}

void PlasmaLoadLight::dataUpdated( const QString &sourceName, 
                                   const Plasma::DataEngine::Data &data )
{
 if( sourceName != "cpu/system/loadavg1" )
     return;
 if( data.keys().count() == 0 )
     return;
 m_load = data[data.keys()[0]].toDouble();
 update();
}

void PlasmaLoadLight::paintInterface( QPainter *painter, 
                                      const QStyleOptionGraphicsItem *option, 
                                      const QRect &contentsRect )
{
 if( m_load < 0.5 )
   painter->setBrush( Qt::green );
 else if( m_load > 0.95 )
   painter->setBrush( Qt::red );
 else
   painter->setBrush( Qt::yellow );
   painter->drawEllipse( contentsRect );

  QFont f;
  f.setPixelSize( contentsRect.height()/4 );
  painter->setFont( f );
  painter->drawText( contentsRect, 
                     Qt::AlignCenter, 
                     QString::number( m_load, 'f', 2 ) );
}

K_EXPORT_PLASMA_APPLET(loadlight, PlasmaLoadLight)

#include "loadlight.moc"