/***************************************************************************
                          kevents.cpp  -  description
                             -------------------
    begin                : Wed Jan 7 2004
    copyright            : (C) 2004-2005 by Christophe Thommeret
    email                : hftom@free.fr
    last modified        : $Date: 2005/08/27 00:35:28 $ by $Author: hftom $
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <qlayout.h>
#include <qfile.h>
#include <qdir.h>
#include <qpopupmenu.h>
#include <qcursor.h>
#include <qwhatsthis.h>

#include <klocale.h>
#include <kiconloader.h>

#include "kevents.h"
#include "channeldesc.h"
#include "dvbevents.h"
#include "dvbstream.h"



EListViewItem::EListViewItem( QListView *parent, QString chanName, QString eBegin, QString eDuration, QString eTitle, EventDesc *desc ) : KListViewItem( parent, chanName, eBegin, eDuration, eTitle )
{
	event = desc;
}



int EListViewItem::compare( QListViewItem *i, int col, bool ascending ) const
{
	EListViewItem *ei = (EListViewItem*)i;

	if ( col != 1 )
		return QListViewItem::compare( i, col, ascending );

	if ( event->startDateTime<ei->event->startDateTime )
		return -1;
	if ( event->startDateTime==ei->event->startDateTime )
		return 0;
	return 1;
}



KEvents::KEvents( QPtrList<ChannelDesc> *chans, QPtrList<DvbStream> *d, QWidget *parent, QSize size ) : QDialog( parent )
{
	dvb = d;
	channels = chans;

	setCaption( i18n("EPG") );

	QGridLayout *grid = new QGridLayout( this, 1, 1, 11, 6, "grid");
	QHBoxLayout *hbox = new QHBoxLayout( 0, 0, 6, "hbox" );

	resetBtn = new KPushButton( i18n("Refresh"), this );
	hbox->addWidget( resetBtn );
	currentNextBtn = new KPushButton( i18n("Current/Next"), this );
	hbox->addWidget( currentNextBtn );
	QSpacerItem* spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
	hbox->addItem( spacer );
	grid->addLayout( hbox, 0, 0 );

	listView = new KListView( this, "listView" );
	listView->addColumn( i18n( "Channel" ) );
	listView->addColumn( i18n( "Begin" ) );
	listView->addColumn( i18n( "Duration" ) );
	listView->addColumn( i18n( "Title" ) );
	listView->setResizePolicy( KListView::AutoOneFit );
	listView->setAllColumnsShowFocus( TRUE );
	listView->setFullWidth( TRUE );
	grid->addWidget( listView, 1, 0 );
	grid->setRowStretch( 1, 4 );

	textBrow = new QTextBrowser( this );
	grid->addWidget( textBrow, 2, 0 );
	grid->setRowStretch( 2, 2 );

	KIconLoader *icon = new KIconLoader();
	resetBtn->setGuiItem( KGuiItem(i18n("Refresh"), icon->loadIconSet("reload", KIcon::Small) ) );
	currentNextBtn->setGuiItem( KGuiItem(i18n("Current/Next"), icon->loadIconSet("toggle_log", KIcon::Small) ) );

	new EListViewItem( (QListView*)listView, "Une chaine", "99/99/99  99:99 9999", "99:99 99", "un titre de programme", 0 );

	resize( size );
	connect( resetBtn, SIGNAL( clicked() ), this, SLOT( reset() ) );
	connect( currentNextBtn, SIGNAL( clicked() ), this, SLOT( setCurrentNext() ) );
	connect( listView, SIGNAL( mouseButtonClicked(int,QListViewItem*,const QPoint&,int) ),
		this, SLOT(mouseClickedSlot(int,QListViewItem*,const QPoint&,int)) );
	connect( listView, SIGNAL(doubleClicked(QListViewItem*,const QPoint &,int)),
		this, SLOT(zap(QListViewItem*,const QPoint &,int)) );

	setMode( 1 );
        delete icon;
}



void KEvents::zap( QListViewItem* it, const QPoint &p, int col )
{
	QPoint pt=p;
	int c=col;
	c++;

	if ( it->text(0) != QString::null )
		emit zapTo( it->text(0) );
}



void KEvents::mouseClickedSlot( int btn, QListViewItem *it, const QPoint &p, int c )
{
	int i=c;
	QPoint pt=p;
	QString s;

	if ( !it )
		return;
	EListViewItem *ei = (EListViewItem*)it;

	switch ( btn ) {
		case Qt::RightButton : {
			QPopupMenu *pop = new QPopupMenu();
			pop->insertItem( i18n("View All Programs"), 1 );
			pop->insertSeparator();
			pop->insertItem( i18n("Add to Timers"), 2 );
			if ( ei->event->running==4 )
				pop->setItemEnabled( 2, false );
			i = 0;
			i = pop->exec( QCursor::pos() );
			switch ( i ) {
				case 0 :
					break;
				case 1 :
					setMode( 2, it->text(0) );
					break;
				case 2 :
					emit addTimer( it->text(0), it->text(3), ei->event->startDateTime, ei->event->duration );
					break;
			}
			delete pop;
			break;
		}
		case Qt::LeftButton : {
			s = "<qt><h3><font color=\"darkblue\">";
			s = s+it->text(0)+"</font></h3>";
			if ( !ei->event->title.isEmpty() ) {
				s = s+"<b><font color=\"darkgreen\"><big>";
				s = s+ei->event->title;
				s = s+"</big></font></b><br>";
			}
			if ( !ei->event->subtitle.isEmpty() ) {
				s = s+"<b><font color=\"#A69631\">";
				s = s+ei->event->subtitle;
				s = s+"</font></b><br>";
			}
			s = s+"<br><font color=\"darkred\">";
			s = s+ei->event->startDateTime.toString()+"<br>";
			s = s+ei->event->duration.toString("hh:mm");
			s = s+"</font><br><br>";
			for ( i=0; i<(int)ei->event->shortEvents.count(); i++ ) {
				s = s+"<p>";
				s = s + ei->event->shortEvents.at(i)->name;
				if (!ei->event->shortEvents.at(i)->name.isEmpty() && !ei->event->shortEvents.at(i)->text.isEmpty()) {
					s = s + " : ";
				}
				s = s + ei->event->shortEvents.at(i)->text;
				s = s + "</p>";
			}
			for ( i=0; i<(int)ei->event->extEvents.count(); i++ ) {
				s = s+ *ei->event->extEvents.at(i);
			}
			s = s+"</qt>";
			textBrow->setText( s );
			break;
		}
	}
}



void KEvents::setCurrentNext()
{
	setMode( 1 );
}



void KEvents::setMode( int m, QString name )
{
	int i;

	mode = m;
	if ( !name.isEmpty() ) {
		currentNextBtn->show();
		for ( i=0; i<(int)channels->count(); i++ ) {
			if ( channels->at(i)->name==name ) {
				chan = channels->at(i);
				break;
			}
		}
	}
	else {
		chan = 0;
		currentNextBtn->hide();
	}
	reset();
}



void KEvents::reset()
{
	listView->clear();
	checkNewEvent();
}



void KEvents::checkNewEvent()
{
	int i, j, k, m, n;
	DVBevents *events=0;
	EventSourceList *slist;
	EventTsidList *tlist;
	EListViewItem *itt=0;
	QString s, t, channel, begin, duration, title;
	bool ret;
	EventDesc *desc;

	for( k=0; k<(int)dvb->count(); k++ ) {
		events = dvb->at(k)->dvbEvents;
		events->mutex.lock();
		for ( m=0; m<(int)events->srcList.count(); m++ ) {
			slist = events->srcList.at(m);
			for ( n=0; n<(int)slist->tsidList.count(); n++ ) {
				tlist = slist->tsidList.at(n);
				for ( j=0; j<(int)tlist->events.count(); j++ ) {
					desc = tlist->events.at(j);
					if ( mode==1 && desc->tid>0x4f )
						continue;

					if ( mode==2 ) {
						if ( !chan )
							continue;
						if ( desc->source!=chan->tp.source || desc->sid!=chan->sid || desc->tsid!=chan->tp.tsid )
							continue;
						channel = chan->name;
					}
					else {
						ret = true;
						for ( i=0; i<(int)channels->count(); i++ ) {
							if ( desc->source==channels->at(i)->tp.source && desc->sid==channels->at(i)->sid && desc->tsid==channels->at(i)->tp.tsid ) {
								channel = channels->at(i)->name;
								ret = false;
								break;
							}
						}
						if ( ret )
							continue;
					}
					begin = desc->startDateTime.toString( Qt::LocalDate );
					duration = desc->duration.toString("hh:mm");
					title = desc->title;
					if ( title.isEmpty() )
						continue;
					itt = new EListViewItem( (QListView*)listView, channel, begin, duration, title, desc );
				}
			}
		}
		events->mutex.unlock();
	}
}



KEvents::~KEvents()
{
}

#include "kevents.moc"
