/*
    This file is part of KWeather.
    Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>

    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 "serviceconfigwidget.h"

#include <QtGui/QImage>
#include <Qt3Support/Q3Header>
#include <QtGui/QPixmap>
#include <QtCore/QByteArray>

#include <kconfig.h>
#include <kdialog.h>
#include <kglobal.h>
#include <k3listview.h>
#include <klocale.h>
#include <kpushbutton.h>
#include <kstandarddirs.h>
#include <ktoolinvocation.h>

#include <serviceinterface.h>

class StationItem : public Q3ListViewItem
{
  public:
    StationItem( Q3ListView *view, const QString &name, const QString &uid )
      : Q3ListViewItem( view, name ), mUID( uid )
    {
    }

    StationItem( Q3ListViewItem *item, const QString &name, const QString &uid )
      : Q3ListViewItem( item, name ), mUID( uid )
    {
    }

    QString uid() const { return mUID; }

  private:
    QString mUID;
};

static void parseStationEntry( const QString &line, QString &name, QString &uid );

ServiceConfigWidget::ServiceConfigWidget( QWidget *parent)
  : wsPrefs( parent), mService(0)
{
  mService = new OrgKdeKweatherServiceInterface( "org.kde.KWeatherService", "/Service", QDBusConnection::sessionBus() );
  connect( mAllStations, SIGNAL(doubleClicked(Q3ListViewItem*,const QPoint&,int)), SLOT(addStation()) );
  connect( mSelectedStations, SIGNAL(doubleClicked(Q3ListViewItem*,const QPoint&,int)), SLOT(removeStation()) );
  connect( mAddButton, SIGNAL(clicked()), this, SLOT(addStation()) );
  connect( mRemoveButton, SIGNAL(clicked()), this,  SLOT(removeStation()) );

  initGUI();
  loadLocations();
  scanStations();
}

ServiceConfigWidget::~ServiceConfigWidget()
{
}

void ServiceConfigWidget::addStation()
{
  if ( !dbusActive() )
    return;

  StationItem *item = dynamic_cast<StationItem*>( mAllStations->selectedItem() );
  if ( item == 0 )
    return;

  mService->addStation( item->uid() );
  scanStations();

  modified();
}

void ServiceConfigWidget::removeStation()
{
  if ( !dbusActive() )
    return;

  StationItem *item = dynamic_cast<StationItem*>( mSelectedStations->selectedItem() );
  if ( item == 0 )
    return;

  mService->removeStation( item->uid() );
  scanStations();

  modified();
}

void ServiceConfigWidget::updateStations()
{
  if ( !dbusActive() )
    return;

  mService->updateAll( );
  scanStations();
}

void ServiceConfigWidget::exitWeatherService()
{
  if ( !dbusActive() )
    return;

  mService->exit();
  modified();
}

void ServiceConfigWidget::scanStations()
{
  if ( !dbusActive() )
    return;

  QStringList list = mService->listStations( );

  mSelectedStations->clear();
  for ( int i = 0; i < list.count(); ++i ) {
    QByteArray iconB = mService->icon( list[ i ] );
    QPixmap pm;
    pm.loadFromData(iconB);
    QImage img = pm.toImage();
    img = img.smoothScale( 22, 22 );
    pm = QPixmap::fromImage( img );

    QString uid = list[ i ];
    if (mStationMap[ uid ].isEmpty())
    {
      mStationMap[ uid ] = uid;
    }
    StationItem *item = new StationItem( mSelectedStations, mStationMap[ uid ], uid );

    item->setPixmap( 0, pm );
  }
}

void ServiceConfigWidget::selectionChanged( Q3ListViewItem *item )
{
  mRemoveButton->setEnabled( item != 0 );
}

void ServiceConfigWidget::modified()
{
  emit changed( true );
}

void ServiceConfigWidget::initGUI()
{
  mAllStations->header()->hide();
  mSelectedStations->header()->hide();
}

void ServiceConfigWidget::loadLocations()
{
  KConfig config( KStandardDirs::locate( "data", "kweatherservice/weather_stations.desktop" ) );

  KConfigGroup group = config.group("Main");
  QStringList regions = group.readEntry("regions").split( ' ');

  QStringList::ConstIterator regionIt;
  for ( regionIt = regions.constBegin(); regionIt != regions.constEnd(); ++regionIt ) {
    group = config.group(*regionIt);
    QString name = group.readEntry( "name" );
    QStringList states = group.readEntry( "states" ).split( ' ' );

    Q3ListViewItem *regionItem = new Q3ListViewItem( mAllStations, name );
    regionItem->setSelectable( false );

    QStringList::ConstIterator stateIt;
    for ( stateIt = states.constBegin(); stateIt != states.constEnd(); ++stateIt ) {
      group = config.group(*regionIt + '_' + *stateIt );
      QString name = group.readEntry( "name" );

      Q3ListViewItem *stateItem = new Q3ListViewItem( regionItem, name );
      stateItem->setSelectable( false );

      QMap<QString, QString> entries = group.entryMap( );
      QMap<QString, QString>::ConstIterator entryIt;
      for ( entryIt = entries.constBegin(); entryIt != entries.constEnd(); ++entryIt ) {
        if ( entryIt.key() != "name" ) {
          QString station, uid;
          // get station and uid from the data
          parseStationEntry( entryIt.data(), station, uid );
          new StationItem( stateItem, station, uid );
          mStationMap.insert( uid, QString( "%1, %2" )
              .arg( station ).arg( *stateIt ) );
        }
      }
    }
  }
}

bool ServiceConfigWidget::dbusActive()
{
  QString error;
  QString appID;
  bool isGood = true;
  if( !QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.KWeatherService")) {
    if ( KToolInvocation::startServiceByDesktopName( "kweatherservice", QStringList(), &error, &appID ) )
      isGood = false;
  }

  return isGood;
}

void parseStationEntry( const QString &line, QString &name, QString &uid )
{
  QStringList list = line.split( ' ');

  bool inName = true;

  for ( int i = 0; i < list.count(); ++i ) {
    if ( inName ) {
      if ( list[ i ].endsWith( "\\" ) ) {
        name.append( list[ i ].replace( "\\", " " ) );
      } else {
        name.append( list[ i ] );
        inName = false;
      }
    } else {
      uid = list[ i ];
      return;
    }
  }
}

#include "serviceconfigwidget.moc"
