//
// C++ Implementation: $MODULE$
//
// Description: 
//
//
// Author: Andreas Silberstorff <andreas@andreas-silberstorff.de>, (C) 2005
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "moviebrowser.h"
#include "kalva.h"
#include "kalvaview.h"

#include <qapplication.h>
#include <qfontmetrics.h>
#include <qrect.h>
#include <qtable.h>
#include <qtooltip.h>
#include <qlistview.h>
#include <qregexp.h>
#include <qstring.h>
#include <qcstring.h>
#include <qstringlist.h>
#include <qdatastream.h>
#include <dcopclient.h>

#include <klocale.h>
#include <kdebug.h>
#include <kprocess.h>
#include <kmessagebox.h>
#include <kpassivepopup.h>
#include <kapplication.h>
#include <kwordwrap.h>

/* default constructor */
movieBrowser::movieBrowser(QWidget* parent, const char* name, WFlags fl)
    :movieBrowserGui(parent,name, fl)
{
}

/* convenience constructor */
movieBrowser::movieBrowser(KalvaView* view,
                             QWidget* parent, const char* name,
                             WFlags fl)
    :movieBrowserGui(parent,name, fl),
     m_view(view)
{
	m_atls     = 0;
	m_atrm     = 0;
	m_buf      = QString::null;
	m_setFocus = false;
	connect( m_movieChooser, SIGNAL( currentChanged(int,int) ),
                 this, SLOT( slotSetTooltip(int,int) ) );
}

movieBrowser::~movieBrowser()
{
}

void movieBrowser::slotRead()
{
    kdDebug() << "In slotRead() " << endl;
    QApplication::disconnect(
          m_movieChooser, SIGNAL(selectionChanged()), 0, 0 );
    m_movieChooser->setCurrentCell(0,0);
    m_movieChooser->setNumRows(0);
    m_buf = QString::null;
    if (!m_atls)  {
       QString cmd = "perl /usr/bin/tvapp.pl -atls";
       m_atls = new KProcess;
       m_atls->setUseShell(true);
       (*m_atls) << cmd;
       QApplication::connect(
           m_atls,         SIGNAL( processExited(KProcess *)),
           this,           SLOT( slotAtlsExited(KProcess *)));
       QApplication::connect(
           m_atls,         SIGNAL( receivedStdout(KProcess *, char*, int)),
           this,           SLOT( slotMoviesReceived(KProcess *, char*, int)));
    }
    m_atls->start(KProcess::NotifyOnExit, KProcess::Stdout);
    //kdDebug() << "Called tvapp.pl " << endl;
}

void movieBrowser::slotMoviesReceived(KProcess *, char* Movie, int)
{
   //kdDebug() << "in slotMoviesReceived(KProcess * proc, char* Serial, int)"
   //          << endl;
   //kdDebug() << "Received Movie " << endl;
   //kdDebug() << Movie << endl;
   m_buf.append(Movie);
}

void movieBrowser::slotAtlsExited(KProcess * proc)
{
   kdDebug() << "in slotAtlsExited(KProcess * proc)" << endl;
   if (! proc->normalExit() ) {
      KMessageBox::detailedSorry   (
         0,
         i18n("tvapp.pl -atls exited with errors."), 
         i18n("tvapp.pl output was:\n%1").arg( proc->exitStatus() ), 
         i18n("tvapp.pl failure")
      );
      kdWarning() << "tvapp.pl -atls exited with status"
                  << proc->exitStatus() << endl;
      kdWarning() << "tvapp.pl exited abnormal" << endl;
      return;
   }
    QStringList s = QStringList::split(";",m_buf,false);
    QRegExp firstKey(".*title*\\s=>\\s");
    QRegExp key(",\\s\\S*\\s=>\\s");
    QString str;
    QString title;

    signed int row    = -1;

    for ( QStringList::Iterator it = s.begin(); it != s.end(); ++it ) {
        str = *it;
        row++;
        m_movieChooser->insertRows(row, 1);
        title = str.section(firstKey,1,1);
        m_movieChooser->setText(row,0,QString::fromUtf8(title.section(key,0,0)));
        m_movieChooser->setText(row,1,QString::fromUtf8(str.section(key,1,1))); // station
        m_movieChooser->setText(row,2,str.section(key,2,2)); // length
        m_movieChooser->setText(row,3,str.section(key,3,3)); // starttime
        m_movieChooser->setText(row,4,str.section(key,4,4)); // startday
        m_movieChooser->setText(row,5,str.section(key,5,5)); // cmd
	QToolTip::add( m_movieChooser->cellWidget(row,5), str.section(key,5,5) );
        m_movieChooser->setText(row,6,str.section(key,6,6)); // jobid
    }
    QApplication::connect(
        m_movieChooser, SIGNAL(selectionChanged()), 
        this,           SLOT( slotEditMovie()));
    emit signalReadingDone();
    //kdDebug() << "Serials loaded" << endl;
}

void movieBrowser::slotSetTooltip(int row,int col)
{
	if ( row < 0 )  {
		return;
	}
	if ( col < 0 )  {
		return;
	}
	QString title = m_movieChooser->text(row,0);
	QString cmd = m_movieChooser->text(row,5);
	if ( title.isNull() )  {
		return;
	}
	if ( cmd.isNull() )  {
		return;
	}
	title.remove('\"');
	cmd.remove('\"');

	QFontMetrics *fm = new QFontMetrics(m_movieChooser->fontMetrics());
	const QRect *rect = new QRect(100,100,300,300);

	KWordWrap * kww = KWordWrap::formatText(
		*fm, 
		*rect, 
		0,
		QString::fromUtf8(cmd), 
		-1
	);
	QString tipp = kww->wrappedString();
 	KPassivePopup::message( tipp, this );
}

void movieBrowser::slotAtrmExited(KProcess * proc)
{
   kdDebug() << "in slotAtrmExited(KProcess * proc)" << endl;
   if (! proc->normalExit() ) {
      KMessageBox::detailedSorry   (
         0,
         i18n("tvapp.pl -atrm exited with errors."), 
         i18n("tvapp.pl output was:\n%1").arg( proc->exitStatus() ), 
         i18n("tvapp.pl failure")
      );
      kdWarning() << "tvapp.pl -atrm exited with status"
                  << proc->exitStatus() << endl;
      kdWarning() << "tvapp.pl exited abnormal" << endl;
      return;
   }
   slotRead();
}

void movieBrowser::slotEditMovie()
{
   //kdDebug() << "in slotEditMovie()" << endl;
   if ( m_movieChooser->numRows() < 0 )
      return;

   int row = m_movieChooser->currentRow();
   kdDebug() << "in slotEditMovie(), currentRow = " << row << endl;
   QString Title     = m_movieChooser->text(row,0);
   if ( Title.isEmpty() )
      return;

   QString Station   = m_movieChooser->text(row,1);
   QString Length    = m_movieChooser->text(row,2);
   QString StartTime = m_movieChooser->text(row,3);
   QString StartDay  = m_movieChooser->text(row,4);
   QString JobId     = m_movieChooser->text(row,6);
   Title.remove("\"");
   Station.remove("\"");
   StartDay.remove("\"");
   m_view->recordMovie (
          Station,
          Title,
          Length,
          StartTime,
          StartDay,
          JobId
   );
}

int movieBrowser::find( const QString & jobId )
{
   for ( int row = 0; row < m_movieChooser->numRows(); row++ )  {
      if ( m_movieChooser->text(row, 6) == jobId )
         return row;
   }
   return 0;
}

void movieBrowser::slotDeleteMovie( const QString & jobid, bool ask )
{
    kdDebug() << "in slotDeleteMovie()" << endl;
    QString Jobid = jobid;
    int row = find (jobid);
    if ( ask )  {
       QString Movie =
           m_movieChooser->text( row,0);
       switch( KMessageBox::warningYesNo(
          this,
          i18n("Do you really want to delete the recording command for the movie %1?").arg(Movie),
          QString::null,
          KStdGuiItem::yes(),
          KStdGuiItem::discard() ) )
       {
         case KMessageBox::No: // Don't save and don't close.
         {
            return;
         }
       }
    }
    if (!m_atrm)  {
       m_atrm = new KProcess;
       QApplication::connect( m_atrm,
                              SIGNAL(processExited(KProcess *)),
                              this,
                              SLOT(slotAtrmExited(KProcess *))
                            );
    }
    m_atrm->clearArguments();
    QString cmd = QString("atrm %1").arg(Jobid);
    m_atrm->setUseShell(true);
    (*m_atrm) << cmd;
    kdDebug() << "Calling " << cmd << endl;
    m_atrm->start(KProcess::NotifyOnExit, KProcess::Stderr);
    return;
}

#include "moviebrowser.moc"
