/***************************************************************************
 *   Copyright (C) 2005-2006 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 <qtable.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qstring.h>
#include <qstringlist.h>

#include "kalva_channellist.h"
#include "savechannellist.h"
#include "settings.h"
#include "prefs.h"
#include "kalvaprofile.h"

#include <klocale.h>
#include <kaction.h>
#include <kdebug.h>
#include <kapplication.h>

KalvaChannellist::KalvaChannellist(QWidget *parent, const char *name)
    : kalvagui_channellistgui(parent, name)
{
	m_channellist = new KalvaProfile( KALVA_CHANNELLIST );
}

KalvaChannellist::~KalvaChannellist()
{
}

/*-------------------------------------------------------------------*
 * PUBLIC SLOTS
 *-------------------------------------------------------------------*/
void KalvaChannellist::slotImport(const QStringList &chlst )
{
    kdDebug() << "received signal chlstImported" << endl;
    QStringList impChlst = chlst;
    setChannellist( impChlst );
    setChanged(true);
}

void KalvaChannellist::slotStationChanged( int, int, int, const QPoint& )
{
   emit signalStationChanged();
}


signed int KalvaChannellist::fuzzyStation( const QString & yourStation )
{
   ///@TODO If more then one station is found close enough then popup a dialog and let the user choose from a list
   QString myStation;
   QString mStation;
   QString yStation;
   for ( int row = 0; row < channellist->numRows(); row++ ) {
      myStation = channellist->text(row,0);
      mStation  = myStation.lower();
      mStation  = mStation.remove( " " );
      yStation  = yourStation.lower();
      yStation  = yStation.remove( " " );
      ///@TODO implement fuzzy compare and return the nearest station name
      if ( mStation == yStation )  {
         return row;
      }
   }
   return -1;
}

QString KalvaChannellist::yourFuzzyStation( const QString & yourStation )
{
   int row = fuzzyStation( yourStation );
   QString myStation;
   if ( row >= 0 )  {
       myStation = channellist->text(row,0);
       return myStation;
   }
   return QString("ERROR: %1").arg(i18n("No matching station found"));
}

bool KalvaChannellist::setStation( const QString & yourStation )
{
   int row = fuzzyStation( yourStation );
   if ( row > -1 )  {
      channellist->clearSelection( );
      channellist->selectRow( row );
      emit signalStationChanged();
      return true;
   }
   return false;
}

/*-------------------------------------------------------------------*
 * Memberfunctions
 *-------------------------------------------------------------------*/
QString KalvaChannellist::station()
{
   return channellist->text(channellist->currentRow(),0);
}

QString KalvaChannellist::channel()
{
   return channellist->text(channellist->currentRow(),1);
}

QString KalvaChannellist::frq()
{
   return channellist->text(channellist->currentRow(),2);
}

bool KalvaChannellist::changed()
{
   return m_changed;
}


/*-------------------------------------------------------------------*
 * PUBLIC functions
 *-------------------------------------------------------------------*/
void KalvaChannellist::loadChannellist()
{
	QString filename = m_channellist->getFilename( Settings::channellist() );
    QFile file( filename );
    if (file.open(IO_ReadOnly) == false)
    {
        kdDebug() << "could not open file " << file.name() << "for reading" << endl;
        return;
    }
    QTextStream chlstFromFile(&file);
    QStringList chlst = QStringList::split("\n",chlstFromFile.read(),false);
    file.close();

    setChannellist( chlst );
    setChanged(false);
}

void KalvaChannellist::slotSaveChannellist()
{
    saveChannellistDlg *dlg = new saveChannellistDlg(this,
                                                     QString::null,
                                                     true,
                                                     0 );
    QString filename;
    if ( dlg->exec() == QDialog::Accepted ) {
       filename = dlg->channellist();
       saveChannellist(filename);
    }
    delete dlg;
}

void KalvaChannellist::saveChannellist(const QString & rFilename)
{
    QFile file(rFilename);
    if (file.open(IO_WriteOnly) == false)
    {
        kdDebug() << "could not open file " << file.name() << "for writing" << endl;
        return;
    }
    QStringList channellist = getChannellist();
    kdDebug() << "got Channellist " << channellist << endl;
    QString chlst = channellist.join("\n");
    QTextStream chlstForFile(&file);
    chlstForFile << chlst;
    file.close();
    Settings::setChannellist(rFilename);
//    KGlobal::config()->sync();
    setChanged(false);
}

void KalvaChannellist::setChanged(bool changed)
{
   m_changed = changed;
}

void KalvaChannellist::setChannellist(QStringList & chlst)
{
    QString str;
    signed int row    = -1;
    channellist->setCurrentCell(0,0);
    channellist->setNumRows(0);
    QStringList Channellist = chlst;

    for ( QStringList::Iterator it = Channellist.begin(); it != Channellist.end(); ++it ) {
        str = *it;
        if (str.contains("[", false))  {
           str = str.remove("[");
           str = str.remove("]");
           row++;
           channellist->insertRows(row, 1);
           channellist->setText(row,0,str);
        }
        if (str.contains("channel=", false))  {
           str = str.remove("channel=");
           channellist->setText(row,1,str);
        }
        if (str.contains("freq=", false))  {
           str = str.remove("freq=");
           channellist->setText(row,2,str);
        }
    }
}

QStringList KalvaChannellist::getChannellist() const
{
    QString str             = "";
    QStringList Channellist = "";

    for ( int row = 0; row < channellist->numRows(); row++ ) {
        str = channellist->text(row, 0);
        Channellist.append(QString("[%1]").arg(str));
        str = channellist->text(row, 1);
        if (!(str.isEmpty()))  {
           Channellist.append(QString("channel=%1").arg(str));
        }
        str = channellist->text(row, 2);
        if (!(str.isEmpty()))  {
           Channellist.append(QString("freq=%1").arg(str));
        }
    }
    return Channellist;
}


#include "kalva_channellist.moc"
