/*
 * kevents.cpp
 *
 * Copyright (C) 2004-2007 Christophe Thommeret <hftom@free.fr>
 *
 * 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.
 *
 * 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 <tqlayout.h>
#include <tqfile.h>
#include <tqdir.h>
#include <tqpopupmenu.h>
#include <tqcursor.h>
#include <tqwhatsthis.h>
#include <tqcheckbox.h>
#include <tqtooltip.h>

#include <tdelocale.h>
#include <kiconloader.h>

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



EListViewItem::EListViewItem( TQListView *parent, TQString chanName, TQString eBegin, TQString eDuration, TQString eTitle, EventDesc *desc ) : TDEListViewItem( parent, chanName, eBegin, eDuration, eTitle )
{
	event = desc;
}



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

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

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



KEvents::KEvents( TQPtrList<ChannelDesc> *chans, TQPtrList<DvbStream> *d, EventTable *t, TQWidget *parent, TQSize size ) : TQDialog( parent )
{
	dvb = d;
	events = t;
	channels = chans;

	setCaption( i18n("Electronic Program Guide") );

	TQGridLayout *grid = new TQGridLayout( this, 1, 1, 11, 6, "grid");
	TQHBoxLayout *hbox = new TQHBoxLayout( 0, 0, 6, "hbox" );
	TQVBoxLayout *vbox = new TQVBoxLayout( 0, 0, 6 , "vbox");

	resetBtn = new KPushButton( i18n("Refresh"), this );
	hbox->addWidget( resetBtn );
	allBtn = new KPushButton( i18n("Scheduled"), this );
	hbox->addWidget( allBtn );
	currentNextBtn = new KPushButton( i18n("Current/Next"), this );
	hbox->addWidget( currentNextBtn );
	currentChannelEpgBtn = new KPushButton( i18n("Current Channel"), this );
	hbox->addWidget( currentChannelEpgBtn );

	TQSpacerItem* spacer = new TQSpacerItem( 20, 20, TQSizePolicy::Expanding, TQSizePolicy::Minimum );
	hbox->addItem( spacer );

	vbox->addLayout( hbox);

	hbox = new TQHBoxLayout();

	searchBtn = new TQToolButton( this );
	searchBtn->setAutoRaise( true );
	TQToolTip::add( searchBtn, i18n("Electronic Program Guide Search"));
	hbox->addWidget( searchBtn );

	TQLabel* filterLabel = new TQLabel( i18n("Search") + ":", this );
	hbox->addWidget( filterLabel );

	searchLineEdit = new KLineEdit(this);
	hbox->addWidget( searchLineEdit );

	tvradioCb  = new TQCheckBox(i18n("TV "), this );
	TQToolTip::add( tvradioCb, i18n("Search TV Channels only (omit Radio)"));
	tvradioCb->setChecked(true);
	hbox->addWidget( tvradioCb);

	titleCb  = new TQCheckBox(i18n("Titles "), this );
	TQToolTip::add( titleCb, i18n("Search Event Titles only (omit Description)"));
	titleCb->setChecked(true);
	hbox->addWidget( titleCb);

	ftaCb  = new TQCheckBox(i18n("FTA "), this );
	TQToolTip::add( ftaCb, i18n("Search Free to Air Channels only (omit PayTV)"));
	ftaCb->setChecked(false);
	hbox->addWidget( ftaCb);

	vbox->addLayout( hbox );

	grid->addLayout( vbox, 0, 0 );

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

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

	TDEIconLoader *icon = new TDEIconLoader();
	resetBtn->setGuiItem( KGuiItem(i18n("Refresh"), icon->loadIconSet("reload", TDEIcon::Small) ) );
	allBtn->setGuiItem( KGuiItem(i18n("Scheduled"), icon->loadIconSet("date", TDEIcon::Small) ) );
	currentNextBtn->setGuiItem( KGuiItem(i18n("Current/Next"), icon->loadIconSet("toggle_log", TDEIcon::Small) ) );
	currentChannelEpgBtn->setGuiItem( KGuiItem(i18n("Current Channel"), icon->loadIconSet("date", TDEIcon::Small) ) );
	searchBtn->setIconSet( icon->loadIconSet("locationbar_erase", TDEIcon::Small) );

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

	resize( size );
	connect( resetBtn			, TQT_SIGNAL( pressed() ), this, TQT_SLOT( reset() ) );
	connect( allBtn				, TQT_SIGNAL( clicked() ), this, TQT_SLOT( setScheduled() ) );
	connect( currentNextBtn		, TQT_SIGNAL( clicked() ), this, TQT_SLOT( setCurrentNext() ) );
	connect( currentChannelEpgBtn, TQT_SIGNAL( clicked() ), this, TQT_SLOT( setCurrentChannelEpg() ) );
	connect( searchBtn, 		  TQT_SIGNAL( clicked() ), this,	 TQT_SLOT(resetSearch()) );
	connect( searchLineEdit, TQT_SIGNAL( returnPressed() ), this, TQT_SLOT( epgSearch() ) );

	connect( listView, TQT_SIGNAL( mouseButtonClicked(int,TQListViewItem*,const TQPoint&,int) ),
		this, TQT_SLOT(mouseClickedSlot(int,TQListViewItem*,const TQPoint&,int)) );

	connect( listView, TQT_SIGNAL(doubleClicked(TQListViewItem*,const TQPoint &,int)),
		this, TQT_SLOT(zap(TQListViewItem*,const TQPoint &,int)) );

	setMode( 1 );
        delete icon;
}

void KEvents::resetSearch()
{
	searchLineEdit->clear();
}

void KEvents::checkEpgSearch(TQString searchword)
{
	int i, j, k, m, n, l;
	EventSource *esrc;
	EventTsid *et;
	EventSid *es;
	EventDesc *desc;
	EListViewItem *itt=0;
	ChannelDesc *ch;
	TQString s, begin, duration, title;
	bool found;

	for( k=0; k<events->getNSource(); k++ ) {
		if ( !(esrc=events->getNEventSource( k )) )
			continue;
		for ( m=0; m<esrc->getNTsid(); m++ ) {
			if ( !(et=esrc->getNEventTsid( m )) )
				continue;
			for ( n=0; n<et->getNSid(); n++ ) {
				if ( !(es=et->getNEventSid( n )) )
					continue;
				for ( j=0; j<es->getNDesc(); j++ ) {
					if ( !(desc=es->getEventDesc( j )) )
						continue;

					if ( desc->title.isEmpty() )
						continue;

					for ( i=0; i<(int)channels->count(); i++ ) {
						ch = channels->at(i);
						if ( desc->source==ch->tp.source && desc->nid==ch->tp.nid && desc->sid==ch->sid && desc->tsid==ch->tp.tsid ) {
							if(tvradioCb->isChecked() && ch->type==2)
								break;

							if(ftaCb->isChecked() && ch->fta==1)
								break;

							found=false;
							if(desc->title.upper().find(searchword.upper())!=-1)
								found=true;

							if(!desc->subtitle.isEmpty()) {
								if(desc->subtitle.upper().find(searchword.upper())!=-1)
									found=true;
							}

							if(!titleCb->isChecked()) {
								if(!found) {
									for ( l=0; l<(int)desc->extEvents.count(); l++ ) {
										s = *desc->extEvents.at(l);
										if(!s.isEmpty()) {
											if(s.upper().find(searchword.upper())!=-1) {
												found=true;
												s="";
												break;
											}
										}
									}
								}
								if(!found) {
									for ( l=0; l<(int)desc->shortEvents.count(); l++ ) {
										s = desc->shortEvents.at(l)->name;
										if(!s.isEmpty()) {
											if(s.upper().find(searchword.upper())!=-1) {
												found=true;
												s="";
												break;
											}
										}
										s = desc->shortEvents.at(l)->text;
										if(!s.isEmpty()) {
											if(s.upper().find(searchword.upper())!=-1) {
												found=true;
												s="";
												break;
											}
										}
									}
								}
							}
							if(!found)
								break;

							begin = TDEGlobal::locale()->formatDateTime( desc->startDateTime );
							duration = desc->duration.toString("hh:mm");
							title = desc->title;

							itt = new EListViewItem( (TQListView*)listView, ch->name, begin, duration, title, desc );

							if ( !ch->pix.isNull() )
								itt->setPixmap( 0, ch->pix );
						}
					}
				}
			}
		}
	}
}

void KEvents::epgSearch()
{

	TQString text = searchLineEdit->text();
	if (text.stripWhiteSpace().isEmpty()) return;

	listView->clear();
	checkEpgSearch(text);
}

void KEvents::setCurrentChannelEpg()
{
	ChannelDesc curchan;
	int i;
	for ( i=0; i<(int)dvb->count(); i++ ) {
		if ( dvb->at(i)->hasLive() ) {
			curchan = dvb->at(i)->getLiveChannel();
			break;
		}
	}
	if ( !curchan.name.isEmpty() )
			setMode( 2, curchan.name );

}

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

	if ( it->text(0) != TQString() )
		emit zapTo( it->text(0) );
}



void KEvents::mouseClickedSlot( int btn, TQListViewItem *it, const TQPoint &p, int c )
{
	int i=c;
	TQPoint pt=p;
	TQString s;

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

	switch ( btn ) {
		case Qt::RightButton : {
			TQPopupMenu *pop = new TQPopupMenu();
			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( TQCursor::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+TDEGlobal::locale()->formatDateTime( ei->event->startDateTime, false )+"<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::setScheduled()
{
	TQListViewItem *it = listView->currentItem();
	if ( !it )
		return;
	setMode( 2, it->text(0) );
}



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

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



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



void KEvents::checkNewEvent()
{
	int i;
	EventSource *esrc;
	EventSid *es;
	EventDesc *desc;
	EListViewItem *itt=0;
	ChannelDesc *ch;
	TQString s, t, channel, begin, duration, title;

	if ( mode==2 ) {
		if ( !chan )
			return;
		if ( !(esrc=events->getEventSource( chan->tp.source )) )
			return;
		if ( !(es=esrc->getEventSid( chan->tp.nid, chan->tp.tsid, chan->sid )) )
			return;
		i = 0;
		while ( (desc=es->getEventDesc(i)) ) {
			++i;
			begin = TDEGlobal::locale()->formatDateTime( desc->startDateTime );
			duration = desc->duration.toString("hh:mm");
			title = desc->title;
			if ( title.isEmpty() )
				continue;
			itt = new EListViewItem( (TQListView*)listView, chan->name, begin, duration, title, desc );
			if ( !chan->pix.isNull() )
				itt->setPixmap( 0, chan->pix );
		}
		return;
	}

	for ( i=0; i<(int)channels->count(); i++ ) {
		ch = channels->at(i);
		if ( (desc=events->getEventDesc( ch->tp.source, ch->tp.nid, ch->tp.tsid, ch->sid, 0 )) ) {
			begin = TDEGlobal::locale()->formatDateTime( desc->startDateTime );
			duration = desc->duration.toString("hh:mm");
			title = desc->title;
			if ( title.isEmpty() )
				continue;
			itt = new EListViewItem( (TQListView*)listView, ch->name, begin, duration, title, desc );
			if ( !ch->pix.isNull() )
				itt->setPixmap( 0, ch->pix );
		}
	}
}



KEvents::~KEvents()
{
}

#include "kevents.moc"
