/***************************************************************************
 *   Copyright (C) 2008 by Swizec <swizec@swizec.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 3 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 "plasma-teacooker.h"

#include <QPainter>
#include <QFontMetrics>
#include <QStyleOptionGraphicsItem>
#include <QSizeF>
#include <QRectF>
#include <QFile>
#include <KGlobalSettings>
#include <QProcess>
#include <QDomDocument>
#include <QTimer>
#include <QDir>
#include <KConfigGroup>
#include <KNotification>
#include <QDesktopWidget>
#include <QApplication>
#include <QGraphicsLinearLayout>
#include <QAction>
#include <KStandardDirs>
#include <QTime>

#include <Phonon/MediaObject>
#include <Phonon/MediaSource>

#include <plasma/svg.h>
#include <plasma/theme.h>
#include <plasma/widgets/icon.h>
#include <plasma/containment.h>
// #include <plasma/tooltipmanager.h>

// K_GLOBAL_STATIC_WITH_ARGS(KComponentData,
// 			  teacookerComponent,
// 			  ("plasma-applet-teacooker",
// 			   QByteArray(),
// 			   KComponentData::SkipMainComponentRegistration))

Plasma_Teacooker::Plasma_Teacooker(
    QObject *parent, const QVariantList &args  )
    : Plasma::Applet(parent, args)
{
   timer = new QTimer(this);

   animCounter = 0;
   animEnd = false;
   timerPause = 100;
   steeping = false;
   
   countdown = "";
   countdownSeconds = 0;
   countdownT = new QTimer( this );
   
   resize(100, 100);
   setHasConfigurationInterface(false);
   setBackgroundHints(DefaultBackground);

   connect(timer, SIGNAL(timeout()), this, SLOT(refresh()));
   connect(countdownT, SIGNAL(timeout()), this, SLOT(refreshCountdown()));

   m_actionResetTea = new QAction("Reset Tea", this);
   connect(m_actionResetTea, SIGNAL(triggered()), this, SLOT(resetTea()));
   m_actionStopTea = new QAction("Stop Tea", this);
   connect(m_actionStopTea, SIGNAL(triggered()), this, SLOT(stopTea()));

   m_teas.insert( "black tea", 3 );
   m_teas.insert( "earl grey", 5 );
   m_teas.insert( "fruit tea", 10 );

   sound = Phonon::createPlayer(Phonon::NotificationCategory,
				Phonon::MediaSource( KStandardDirs::locate( "sound", "KDE-Sys-App-Positive.ogg" ) )
			      );
}
 
Plasma_Teacooker::~Plasma_Teacooker()
{
   timer->stop();
   delete timer;
   delete m_actionResetTea;
   delete m_actionStopTea;
   delete countdownT;
   delete sound;
}

void Plasma_Teacooker::init()
{
   createMenu();
}

void Plasma_Teacooker::refresh()
{
    timer->stop();
    if ( steeping )
    {
	animCounter++;

	if ( !animEnd )
	{
	    timer->setInterval( timerPause ); 
	    timer->start();
	}
    }

    update();
    emit contentsChanged();
}

void Plasma_Teacooker::refreshCountdown()
{
    countdownT->stop();
    
    if ( steeping )
    {
	countdownSeconds--;

	countdown = QTime( 0, countdownSeconds/60, countdownSeconds%60 ).toString( "mm:ss" );

	countdownT->setInterval( 1000 );
	countdownT->start();
    }

    update();
    emit contentsChanged();
}

void Plasma_Teacooker::paintInterface(QPainter *p,
        const QStyleOptionGraphicsItem *option, const QRect &contentsRect)
{
    Q_UNUSED( option );

    int delta = (int)contentsRect.height()/10*2;
    p->setRenderHint(QPainter::SmoothPixmapTransform);
    p->setRenderHint(QPainter::Antialiasing);

    if ( !animEnd )
    {
	QRect imageRect(contentsRect.left(), contentsRect.top()+delta,
	      (int)contentsRect.width(), (int)contentsRect.height()-delta);
	paintImage(p, imageRect);
    }else
    {
	QRect imageRect(contentsRect.left(), contentsRect.top(),
	      (int)contentsRect.width(), (int)contentsRect.height());
	paintImage(p, imageRect);
    }

    QRect textRect(contentsRect.left(), contentsRect.top()+(contentsRect.height()/3.0)*2-5,
          (int)(contentsRect.width() ), (int)contentsRect.height()/2.0);

    if ( !animEnd )
    {
	p->setPen(Qt::black);
	p->setFont( QFont("FreeSans", textRect.height()/2+2, QFont::Bold ) );
	p->drawText(textRect, Qt::AlignCenter, countdown);
    
	p->setPen(Qt::white);
	p->setFont( QFont("FreeSans", textRect.height()/2, QFont::Bold ) );
	p->drawText(textRect, Qt::AlignCenter, countdown);
    }else
    {
	p->setPen(Qt::black);
	p->setFont( QFont("FreeSans", textRect.height()/3+2, QFont::Bold ) );
	p->drawText(textRect, Qt::AlignCenter, countdown);
	
	p->setPen(Qt::red);
	p->setFont( QFont("FreeSans", textRect.height()/3, QFont::Bold ) );
	p->drawText(textRect, Qt::AlignCenter, countdown);
    }
    
    p->save();
    p->restore();
}

void Plasma_Teacooker::paintImage( QPainter *p, const QRect &imageRect )
{
    QString svg_file = QString();

    svg_file = "widgets/teacooker";
    
    Plasma::Svg* svg;
    svg = new Plasma::Svg(this);
    svg->setImagePath( svg_file );
    svg->setContainsMultipleImages(true);
    svg->resize(imageRect.width(), imageRect.height());

    if ( animCounter == 0 )
    {
	svg->paint(p, imageRect, "empty" );
    }else if ( animCounter > 12 )
    {
	animEnd = true;
	steeping = false;
	svg->paint(p, imageRect, "done" );
	teaDone( m_activeTea );
    }else
    {
	QString num;
	num = QString( "%1" ).arg( animCounter );
	
	svg->paint(p, imageRect, "steeping"+num );
    }
}

// this way will be used when tooltipmanager.h becomes available outside SVN
void Plasma_Teacooker::createMenu()
{
//     QAction* open = new QAction(SmallIcon("document-open"),i18n("&Open"), this);
//     actions.append(open);
//     connect(open, SIGNAL(triggered(bool)), this , SLOT(slotOpen()));
// 
//     m_menu.addTitle(i18n("Trash"));
//     m_menu.addAction(open);
//     m_menu.addAction(emptyTrash);
// 
//     //add the menu as an action icon
//     QAction* menu = new QAction(SmallIcon("arrow-up-double"),i18n("&Menu"), this);
//     connect(menu, SIGNAL(triggered(bool)), this , SLOT(popup()));
//     m_icon->addIconAction(menu);
}

void Plasma_Teacooker::popup()
{
//     if (m_menu.isVisible()) {
//         m_menu.hide();
//         return;
//     }
//     m_menu.popup(popupPosition(m_menu.sizeHint()));
//     m_icon->setPressed();
}

void Plasma_Teacooker::slotOpen()
{
//     emit releaseVisualFocus();
//     KRun::runUrl(m_trashUrl, "inode/directory", 0);
}

void Plasma_Teacooker::pressed()
{
//     emit releaseVisualFocus();
//     KRun::runUrl(m_trashUrl, "inode/directory", 0);
}

void Plasma_Teacooker::startTea( )
{
    QAction *tmp = qobject_cast<QAction*>(sender());

    m_activeTea = tmp->data().toString();
    countdownSeconds = m_teas.value( m_activeTea )*60;
    countdown = "";
    timerPause = countdownSeconds*1000/12;
    steeping = true;
    refreshCountdown();
    refresh();
}

void Plasma_Teacooker::resetTea()
{
    animCounter = 0;
    animEnd = false;
    steeping = false;
    countdown = "";

    update();
}

void Plasma_Teacooker::stopTea()
{
    steeping = false;
    countdown = "";

    update();
}

Qt::Orientations Plasma_Teacooker::expandingDirections() const
{
    // no use of additional space in any direction
    return 0;
}

QList<QAction*> Plasma_Teacooker::contextualActions()
{
	QList<QAction*> actions;

	if ( !steeping )
	{
	    QAction *tmp;
	    for(QMap<QString,int>::const_iterator it = m_teas.begin(); it != m_teas.end(); ++it) {
		    QString tea = QString( "Steep "+it.key()+" (%1min)" ).arg( m_teas.value( it.key() ) );
		    tmp = new QAction( tea, this);
		    tmp->setData(it.key());
		    connect(tmp, SIGNAL(triggered()), this, SLOT(startTea()));
		    actions << tmp;
	    }
	    if ( animEnd )
	    {
		actions << m_actionResetTea;
	    }
	}else if ( !animEnd )
	{
	    actions << m_actionStopTea;
	}else
	{
	    actions << m_actionResetTea;
	}

	return actions;
}

void Plasma_Teacooker::teaDone( QString tea )
{
//     because there seems to be no way of making knotify work let's just play something through phonon
    
    sound->play();

    countdown = tea;
    
//     KNotification *notify=new KNotification("kopete_contact_incoming");

//     notify->setText("<qt><em>"+tea+"</em> is now ready</qt>");
//     notify->sendEvent();
//     KNotification::event( "kopete_contact_incoming", "Blablabla" );
/*	QPixmap m_pix=QPixmap( "widgets/teacooker" );
	
	QString content=i18n("<qt><em>%1</em> is now ready</qt>", tea);
	KNotification::event( "teacooker_teaReady",
			content,
			m_pix,
			0L,
			KNotification::CloseOnTimeout,
			*teacookerComponent);*/
}

#include "plasma-teacooker.moc"
