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

#include <qapplication.h>
#include <qfontmetrics.h>
#include <qrect.h>
#include <qtable.h>
#include <qlistview.h>
#include <qregexp.h>
#include <qstring.h>
#include <qcstring.h>
#include <qstringlist.h>
#include <qdatastream.h>
#include <dcopclient.h>
#include <qvbox.h>
#include <qlabel.h>
#include <qhbox.h>
#include <qpushbutton.h>

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

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

/* convenience constructor */
serialBrowser::serialBrowser(KalvaView* view,
                             QWidget* parent, const char* name,
                             WFlags fl)
    :serialBrowserGui(parent,name, fl),
     m_view(view)
{
	m_cronls     = 0;
	m_cronrm     = 0;
	m_buf        = QString::null;
	connect( m_serialChooser, SIGNAL( currentChanged(int,int) ),
                 this, SLOT( slotSetTooltip(int,int) ) );
}

serialBrowser::~serialBrowser()
{
}

void serialBrowser::slotRead()
{
    //kdDebug() << "In slotRead() " << endl;
    m_serialChooser->setCurrentCell(0,0);
    m_serialChooser->setNumRows(0);
    m_buf = QString::null;
    if (!m_cronls)  {
       QString cmd = "perl /usr/bin/tvapp.pl -cronls";
       m_cronls = new KProcess;
       m_cronls->setUseShell(true);
       (*m_cronls) << cmd;
       QApplication::connect(
           m_cronls, SIGNAL( processExited(KProcess *)),
           this,     SLOT( slotCronlsExited(KProcess *)));
       QApplication::connect(
           m_cronls, SIGNAL( receivedStdout(KProcess *, char*, int)),
           this,     SLOT( slotSerialsReceived(KProcess *, char*, int)));
    }
    m_cronls->start(KProcess::NotifyOnExit, KProcess::Stdout);
    //kdDebug() << "Called tvapp.pl " << endl;
}

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

void serialBrowser::slotCronlsExited(KProcess * proc)
{
   kdDebug() << "in slotCronlsExited(KProcess * proc)" << endl;
   if (! proc->normalExit() ) {
      KMessageBox::detailedSorry   (
         0,
         i18n("tvapp.pl -cronls exited with errors."), 
         i18n("tvapp.pl output was:\n%1").arg( proc->exitStatus() ), 
         i18n("tvapp.pl failure")
      );
      kdWarning() << "tvapp.pl -cronls exited with status"
                  << proc->exitStatus() << endl;
      kdWarning() << "tvapp.pl exited abnormal" << endl;
      return;
   }
    //kdDebug() << endl;
    //kdDebug() << "-----------------" << endl;
    //kdDebug() << m_buf << endl;
    //kdDebug() << "-----------------" << endl;
    //kdDebug() << endl;
    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_serialChooser->insertRows(row, 1);
        title = str.section(firstKey,1,1);
        m_serialChooser->setText(row,0,QString::fromUtf8(title.section(key,0,0)));
        m_serialChooser->setText(row,1,QString::fromUtf8(str.section(key,1,1))); // station
        m_serialChooser->setText(row,2,str.section(key,2,2)); // duration
        m_serialChooser->setText(row,3,str.section(key,3,3)); // starttime
        m_serialChooser->setText(row,4,str.section(key,4,4)); // daysoftheweek
        m_serialChooser->setText(row,5,str.section(key,5,5)); // cmd
    }
    //kdDebug() << "Serials loaded" << endl;
}

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

	QFontMetrics *fm = new QFontMetrics(m_serialChooser->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 serialBrowser::slotCronrmExited(KProcess * proc)
{
   kdDebug() << "in slotCronrmExited(KProcess * proc)" << endl;
   if (! proc->normalExit() ) {
      KMessageBox::detailedSorry   (
         0,
         i18n("tvapp.pl -cronrm exited with errors."), 
         i18n("tvapp.pl output was:\n%1").arg( proc->exitStatus() ), 
         i18n("tvapp.pl failure")
      );
      kdWarning() << "tvapp.pl -cronrm exited with status"
                  << proc->exitStatus() << endl;
      kdWarning() << "tvapp.pl exited abnormal" << endl;
      return;
   }
   //kdDebug() << "Serial deleted, read anew" << endl;
   slotRead();
}

void serialBrowser::slotEditSerial()
{
   //kdDebug() << "in slotEditSerial()" << endl;
   if ( m_serialChooser->numRows() <= 0 )
      return;

   int row = m_serialChooser->currentRow();
   QString Title     = m_serialChooser->text(row,0);
   if ( Title.isEmpty() )
      return;
   QString Station   = m_serialChooser->text(row,1);
   QString Length    = m_serialChooser->text(row,2);
   QString StartTime = m_serialChooser->text(row,3);
   QString DOWs      = m_serialChooser->text(row,4);
   Title.remove("\"");
   Station.remove("\"");
   DOWs.remove("\"");
   m_view->recordSerial (
          Station,
          Title,
          Length,
          StartTime,
          DOWs
   );
}


void serialBrowser::slotDeleteSerial()
{
    kdDebug() << "in slotDeleteSerial()" << endl;
    QString Serial = m_serialChooser->text(m_serialChooser->currentRow(),0);
    switch( KMessageBox::warningYesNo(
       this,
       i18n("Do you really want to delete the recording command for the serial %1?").arg(Serial),
       QString::null,
       KStdGuiItem::yes(),
       KStdGuiItem::discard() ) )
    {
      case KMessageBox::Yes:
      {
         if (!m_cronrm)  {
            m_cronrm = new KProcess;
            QApplication::connect(m_cronrm, SIGNAL(processExited(KProcess *)),
                                  this, SLOT(slotCronrmExited(KProcess *)));
         }
         m_cronrm->clearArguments();
         QString cmd = QString("perl /usr/bin/tvapp.pl -film %1  -cronrm")
                              .arg(Serial);
         m_cronrm->setUseShell(true);
        (*m_cronrm) << cmd;
         kdDebug() << "Calling " << cmd << endl;
         m_cronrm->start(KProcess::NotifyOnExit, KProcess::Stderr);
	 return;
      }
      case KMessageBox::No: // Don't save and don't close.
	 return;
    }

}

#include "serialbrowser.moc"
