/***************************************************************************
                          kscore.cpp  -  description
                             -------------------
    begin                : Sat Aug  5 22:10:22 EDT 2000
    copyright            : (C) 2000 by Jonathan Singer
    email                : jsinger@leeta.net
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software and can be used or redistributed        *
 *   subject to the included license.                                      *
 *                                                                         *
 ***************************************************************************/

#include <qnamespace.h>
#include <qpainter.h>
#include <kapp.h>
#include <kglobal.h>
#include <klocale.h>
#include <kconfig.h>
#include <kaboutdata.h>
#include "kscore.h"
#include "kscore_pref.h"
#include <qpen.h>
#include <qevent.h>
#include <stdio.h>
#include <qfile.h>
#include <qmessagebox.h>
#include <qtextstream.h>
#include <qregexp.h>
#include <kprocess.h>
#include <iostream.h>
#include <kurl.h>
#include <kio/netaccess.h>
#include <unistd.h>
#include <krun.h>




extern "C"
{
  KPanelApplet* init(QWidget *parent, const QString& configFile)
  {
	KGlobal::locale()->insertCatalogue("kscoreapplet");
	return new KscoreApplet(configFile, KPanelApplet::Normal,
                             KPanelApplet::About | KPanelApplet::Help | KPanelApplet::Preferences,
                             parent, "kscore");
  }
}

KscoreApplet::KscoreApplet(const QString& configFile, Type type, int actions,
                             QWidget *parent, const char *name)
  : KPanelApplet(configFile, type, actions, parent, name)
{
Downloading = false;
KConfig* c = config();
c->setGroup("Settings");
League = (c->readEntry("League", "mlb" ));
Team = (c->readEntry("Team", "bos" ));
Text_color = (c->readColorEntry("Color", &black));
Interval = (c->readNumEntry("Interval", 15 ));
Online = (c->readBoolEntry("Online", true ));

PID.setNum( getpid() );
getData();

menu = new KPopupMenu();
menu->insertItem( i18n("Settings"), 1 );
menu->insertItem( i18n("Online"), 2 );
menu->insertSeparator();
menu->insertItem( i18n("Help"), 3 );
//menu->insertItem( i18n("Report Bug"), 4 );
menu->insertItem( i18n("About"), 5 );
//menu->insertItem( i18n("About KDE"), 6 );
menu->setItemChecked( 2, Online);

/*KAboutData data( "kscore", I18N_NOOP("KScore"),  "0.1", I18N_NOOP("Sports
score ticker for the KDE panel"), 	KAboutData::License_BSD, "(c) 2000,
Jonathan Singer", 	"http://www.leeta.net/kscore", 	"\n", "jsinger@leeta.net");
data.addAuthor("Jonathan Singer",0, "jsinger@leeta.net"); */

//hmenu = new KHelpMenu(this, &data, 0);


hmenu = new KHelpMenu(this, "Kscore written by Jonathan Singer\n\n"
						          "jsinger@leeta.net", 0);

connect(&proc, SIGNAL(receivedStdout(KProcess *, char *, int)), this,
       SLOT(readOutput(KProcess *, char *, int )));

connect(&proc, SIGNAL(processExited(KProcess *)), this,
     SLOT(finishOutput(KProcess * )));

connect(&Timer, SIGNAL(timeout()), this, SLOT(getData()));


}


void  KscoreApplet::getData()
{
if ( Online && (!Downloading) )
    {
       Timer.start( Interval*60*1000, false );
       Downloading = true;
       QString URL;
       URL = "http://sports.excite.com/";
       URL += League;

//          URL = "/tmp/mlb.html";
//       cout << "Downloading " << URL.latin1() << "\n";
       Scoreboard = QString::null;

       QString localFile = "/tmp/kscore_temp";

       const KURL reportURL(URL);
       const KURL dataURL(localFile);
       //restore when set
       theJob = new KIO::FileCopyJob(reportURL,  dataURL, 777, false, true, false, false);
       connect( theJob, SIGNAL( result( KIO::Job *)), this, SLOT( loadFile(KIO::Job *)));        //remove
    }
}

void  KscoreApplet::readOutput( KProcess *, char *buffer, int buflen)
{
    Output += QString::fromLatin1( buffer, buflen );
}

void  KscoreApplet::finishOutput( KProcess *)
{
    proc.kill();

    //parse Output
    Output.replace(QRegExp("_")," ");
    HomeName = Output.left(Output.find("\n"));
    Output = Output.remove(0,(Output.find("\n")+1));
    HomeScore = Output.left(Output.find("\n"));
    Output = Output.remove(0,(Output.find("\n")+1));
    VisitorsName = Output.left(Output.find("\n"));
    Output = Output.remove(0,(Output.find("\n")+1));
    VisitorsScore = Output.left(Output.find("\n"));
    Output = Output.remove(0,(Output.find("\n")+1));
    Period = Output.left(Output.find("\n"));
    Output = Output.remove(0,(Output.find("\n")+1));
    Date = Output.left(Output.find("\n"));

    update();
    Downloading = false;
}

void  KscoreApplet::paintEvent( QPaintEvent * )
{
    QPainter p( this );
    p.setPen( Text_color );
    if ( orientation() == Horizontal )
    {
        if (VisitorsName == "NO SCORE")
        {
            p.setFont( QFont( "times", 9, QFont::Bold ) );
            p.drawText( 26, 16, i18n("NO  SCORE"));
            p.drawText( 23, 32, i18n("AVAILABLE"));
         }
       else
       {
            p.setFont( QFont( "times", 9, QFont::Bold ) );
//					p.setFont( QFont( "times", 9 ) );
            p.drawText( 3, 12, HomeName.left( 11 ));
            p.drawText( 3, 24, VisitorsName.left(  11 ));
            p.drawText( 73,  0, 12, 14, AlignBottom | AlignRight,  HomeScore);
            p.drawText( 73, 12, 12, 14, AlignBottom | AlignRight, VisitorsScore);
//					p.drawText( 76, 12, HomeScore);
//					p.drawText( 76, 24, VisitorsScore);
            p.drawText( 3, 36, Period);
            p.drawText( 48, 36, Date);
        }
    }
    else {
        if (VisitorsName == "NO SCORE") {
            p.setFont( QFont( "times", 8, QFont::Bold ) );
            p.drawText( 13, 20, i18n("NO") );
            p.drawText( 6, 33, i18n("SCORE") );
        }
        else
        {
//					p.setFont( QFont( "times", 9 ) );
            p.setFont( QFont( "times", 9, QFont::Bold ) );
            p.drawText( 2, 12, HomeName.left( 4 ));
            p.drawText( 2, 22, VisitorsName.left( 4 ));
            p.drawText( 28,  2, 14, 12, AlignBottom | AlignRight, HomeScore);
            p.drawText( 28, 12, 14, 12, AlignBottom | AlignRight, VisitorsScore);
            p.drawText( 2, 35, Period);
            p.drawText( 2, 45, Date.right( Date.length()-4 ) );
        }
    }
}

void KscoreApplet::mousePressEvent( QMouseEvent *event)
{
if (event->button() == QMouseEvent::RightButton )
	{
	int result = menu->exec( QCursor::pos() );
	if (result == 1)
			{
				pref_dialog *pref= new pref_dialog( League, Team, Text_color, Interval, this	);
				pref->show();
				connect( pref, SIGNAL(results(QString, QString, QColor, int)), this,
				SLOT(changeSettings(QString, QString, QColor, int))     );
      	}
      else if (result == 2)
        {
            Online = !Online;
            menu->setItemChecked( 2, Online);
            KConfig* c = config();
            c->writeEntry("Online", Online );
            c->sync();
			if (Online)
                {
			 		getData();
                }
        }
      else if (result == 3)
        {
// 	       	hmenu->appHelpActivated();
            KRun::runCommand( "khelpcenter help:/kscore/index.html", "khelpcenter", "khelpcenter" );
        }
      else if (result == 4)
        {
         	hmenu->reportBug();
        }
      else if (result == 5)
        {
         	hmenu->aboutApplication();
        }
      else if (result == 6)
        {
         	hmenu->aboutKDE();
        }


	}
if (event->button() == QMouseEvent::LeftButton )

        {
			getData();
    	}

}

void KscoreApplet::loadFile( KIO::Job *aJob )
{
	// data
	if (!aJob->error())
  {
        QString dataDir = "/tmp/kscore_temp";
//			QString dataDir = "mlb.html";
        QFile f(dataDir);
				if ( f.open(IO_ReadOnly) ) {    // file opened successfully
        		QTextStream t( &f );        // use a text stream
        		while ( !t.eof() ) {        // until end of file...
            	Scoreboard = t.read();       // line of text excluding '\n'
            }
//            cout << "Download worked!\n";
            f.close();
            }

	QFile::remove ( dataDir );
	Scoreboard.insert(0, "\n"); Scoreboard.insert(0, Team );
    Scoreboard.insert(0, "\n"); Scoreboard.insert(0, League );
    //Parse scoreboard
    Output = QString::null;

	proc.clearArguments();
	proc << "kscore_excite.pl";


	proc.start(KProcess::NotifyOnExit, KProcess::All);

	proc.writeStdin(Scoreboard.latin1(), Scoreboard.length());
	proc.closeStdin();
 	}
	else
	{

		QPainter p( this );
		p.setPen( Text_color );
		p.eraseRect( this->rect() );
		if ( orientation() == Horizontal )
			{
					p.setFont( QFont( "times", 9, QFont::Bold ) );
					p.drawText( 5, 25, i18n("DOWNLOAD FAILED") );
			}

		else
			{
					p.setFont( QFont( "times", 8, QFont::Bold ) );
  					p.drawText( 14, 22, i18n("D/L") );
					p.drawText( 3, 35, i18n(" FAILED") );
			}


	}


}

void KscoreApplet::changeSettings( QString newLeague, QString newTeam, QColor newColor, int newInterval )
{
League = newLeague; Team = newTeam;
Text_color = newColor; Interval = newInterval;

KConfig* c = config();
c->setGroup("Settings");
c->writeEntry("League", League );
c->writeEntry("Team", Team );
c->writeEntry("Color", Text_color);
c->writeEntry("Interval", Interval );
c->sync();

getData();
}


int KscoreApplet::widthForHeight(int ) const
{
  return 101;
}

int KscoreApplet::heightForWidth(int ) const
{
  return 50;
}


#include <kscore.moc>
