/*
 *   Copyright 2009 Johan Thelin <e8johan@gmail.com>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Library General Public License as
 *   published by the Free Software Foundation; either version 2 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 Library 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 "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"
