/***************************************************************************
 *   Copyright (C) 2005 by Andreas Silberstorff   *
 *   ml@andreas-silberstorff.de   *
 *                                                                         *
 *   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 Steet, Fifth Floor, Boston, MA 02110-1301, USA.             *
 *                                                                         *
 *   In addition, as a special exception, the copyright holders give       *
 *   permission to link the code of this program with any edition of       *
 *   the Qt library by Trolltech AS, Norway (or with modified versions     *
 *   of Qt that use the same license as Qt), and distribute linked         *
 *   combinations including the two.  You must obey the GNU General        *
 *   Public License in all respects for all of the code used other than    *
 *   Qt.  If you modify this file, you may extend this exception to        *
 *   your version of the file, but you are not obligated to do so.  If     *
 *   you do not wish to do so, delete this exception statement from        *
 *   your version.                                                         *
 ***************************************************************************/

#include "scantvplugin.h"
#include <kchlstfilterplugin.h>

#include <qregexp.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qapplication.h>

#include <kgenericfactory.h>
#include <kaction.h>
#include <kprocess.h>
#include <kprogress.h>
#include <kmessagebox.h>

#include <kdebug.h>

K_EXPORT_COMPONENT_FACTORY( scantvplugin, KGenericFactory<scantvPlugin>( "scantvplugin" ) )

scantvPlugin::scantvPlugin(QObject *parent, const char* name, const QStringList&)
            : KChlstFilterPlugin::Plugin(parent, name )
{
    // Tell the host application to load my GUI component
    setInstance(KGenericFactory<scantvPlugin>::instance());

    // Create the actions of thus plugin
    m_actionImport = new KAction (i18n("scan with scantv"), "file",
                           0,
                           this, SLOT(slotImport()),
                           actionCollection(), "scantv");

    setXMLFile("scantvpluginui.rc", true);

    m_actionImport->setEnabled(true);
    // For ease announce that we have been loaded.
    kdDebug() << "scantvPlugin plugin loaded" << endl;
}


/***********************************************************************
 * this is the most simple example for an import filter because
 * this format is native and allmost no translation is needed.
 *
 ***@TODO: filter out options not relevant (see "man xawtvrc")
 ***********************************************************************/
void scantvPlugin::slotImport()
{
    //kdDebug() << "scantvPlugin::slotImport() has been called" << endl;
    m_proc = new KProcess;
    QString scantv     = channellistInterface()->scantv();
    QString tvnorm     = channellistInterface()->tvnorm();
    QString videodev   = channellistInterface()->videodev();
    QString vbidev     = channellistInterface()->vbidev();
    QString freq_table = channellistInterface()->freq_table();

    (*m_proc) << scantv
              << "-n" << tvnorm
              << "-f" << freq_table
              << "-c" << videodev
              << "-C" << vbidev;

    m_buf = QString::null;

    QApplication::connect(m_proc, SIGNAL(processExited(KProcess *)),
                          this, SLOT(slotScantvExited(KProcess *)));
    QApplication::connect(m_proc, SIGNAL(receivedStdout(KProcess *, char*, int)),
                          this, SLOT(slotChlstReceived(KProcess *, char*, int)));
    QApplication::connect(m_proc, SIGNAL(receivedStderr(KProcess *, char*, int)),
                          this, SLOT(slotChlstReceived(KProcess *, char*, int)));
    m_proc->start(KProcess::NotifyOnExit, KProcess::Stderr);

    QString cap  = i18n("scantv");
    QString text = i18n("Scanning for tv stations.\n\nIt is normal when the progress bar stays at 30% for about a minute or so,\nthat is the time scantv is working.\n\nThis may take a while, so please be patient.\n\nHint: If You start kalva from the konsole You can see the scantv output.");
    Q_ASSERT(m_progress == 0);
    m_progress = new KProgressDialog(0, 0, cap, text);
    m_progress->progressBar()->setTotalSteps(100);
    m_progress->setAllowCancel(true);
    //progressDialog->incInitialSize(QSize(100, 0), true);
    m_progress->disableResize();
    m_progress->show();
}

void scantvPlugin::slotScantvExited(KProcess *proc)
{ 
   if (proc->normalExit() == true) {
      kdDebug() << "Channellist was created by scantv" << endl;
   }  else  {
      KMessageBox::detailedSorry   (
         0,
         i18n("Scantv exited with errors."), 
         i18n("Scantv output was:\n%1").arg( proc->exitStatus() ), 
         i18n("Scantv failure")
      );
      kdWarning() << "scantv exited abnormal" << endl;
      m_progress->progressBar()->setProgress(100);
      return;
   }

    QString stations = m_buf;
    QStringList scantvChlst = QStringList::split("\n",stations,false);
    stations = QString::null;
    QString str;
    int progress = 0;

    for ( QStringList::Iterator it = scantvChlst.begin(); it != scantvChlst.end(); ++it ) {
       str = *it;
       if ( ! ( str.contains ("no station") ) )
       {
           kdDebug() << "str = " << str << endl;
           str = str.simplifyWhiteSpace();
           str = str.remove("(");
           str = str.replace(" MHz):", "0");
           str = str.replace("???", i18n("unknown Station"));
           stations.append( QString( "[%1]\nchannel=%2\nfreq=%3\n" )
                            .arg( str.section(" ",2) )
                            .arg( str.section(" ",0,0) )
                            .arg( str.section(" ",1,1)   )
                          );
       }
       if ( progress < 99 )  {
          progress += 1;
          m_progress->progressBar()->advance(1);
       }  else  {
          progress = 0;
          m_progress->progressBar()->advance(-1);
       }
    }
    QStringList chlst = QStringList::split("\n",stations,false);

    if (m_progress) {
       m_progress->progressBar()->setValue
         (m_progress->progressBar()->totalSteps());
    }
    delete m_progress;
    m_progress = 0;
    emit chlstImported( chlst );
}

void scantvPlugin::slotChlstReceived(KProcess *, char* stdOutChlst, int)
{
    //kdDebug() << "stdOutChlst = " << stdOutChlst << endl;
    m_progress->progressBar()->advance(1);
    QString str( stdOutChlst );
    QString freq_table = channellistInterface()->freq_table();
    str.remove(QString("scanning channel list %1...\n").arg(freq_table));
    //? str.remove ((QRegExp)"\n$");
    m_buf.append(str);
    kdDebug() << "str = " << endl;
    kdDebug() << str << endl;

    // Here we have to translate this line
    //      E8   (196.25 MHz): ZDF
    // into the three lines
    //      [ZDF]
    //      channel=E8
    //      freq=196.250
    // for each station

}

void scantvPlugin::slotExport()
{
    kdDebug()   << "scantvPlugin::slotExport() has been called" << endl;
    kdWarning() << "The scantv plugin is not supposed to have an export option." << endl;
}

#include "scantvplugin.moc"
