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

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include <tdeaboutdata.h>
#include <tdeapplication.h>
#include <tdecmdlineargs.h>
#include <ksimpleconfig.h>
#include <kdebug.h>
#include <tdeglobal.h>
#include <tdelocale.h>
#include <kstandarddirs.h>

#include <tdeabc/stdaddressbook.h>
#include <libtdepim/distributionlist.h>

static const TDECmdLineOptions options[] =
{
  { "disable-autostart", "Disable automatic startup on login", 0 },
  TDECmdLineLastOption
};

void convertDistributionLists()
{
  KSimpleConfig cfg( locateLocal( "data", "tdeabc/distlists" ) );
  const TQMap<TQString, TQString> entryMap = cfg.entryMap( "DistributionLists" );

  if ( entryMap.isEmpty() ) // nothing to convert
    return;

  TQMapConstIterator<TQString, TQString> it;
  for ( it = entryMap.begin(); it != entryMap.end(); ++it ) {
    const TQString listName = it.key();
    const TQStringList entries = TQStringList::split( ',', it.data(), true );

    KPIM::DistributionList distList;
    distList.setUid( TDEApplication::randomString( 10 ) );
    distList.setName( listName );

    if ( entries.count() > 1 ) {
      for ( uint i = 0; i < entries.count(); i += 2 ) {
        const TQString uid = entries[ i ];
        const TQString preferredEMail = entries[ i + 1 ];

        distList.insertEntry( uid, preferredEMail );
      }
    }

    TDEABC::StdAddressBook::self()->insertAddressee( distList );
  }

  TDEABC::StdAddressBook::self()->save();
}

int main( int argc, char **argv )
{
  TDEApplication::disableAutoDcopRegistration();

  TDEAboutData aboutData( "tdeabcdistlistupdater", "Converter tool for distribution lists", "0.1" );
  aboutData.addAuthor( "Tobias Koenig", 0, "tokoe@kde.org" );

  TDECmdLineArgs::init( argc, argv, &aboutData );
  TDECmdLineArgs::addCmdLineOptions( options );

  TDEApplication app( false, false );

  TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs();

  if ( args->isSet( "disable-autostart" ) ) {
    kdDebug() << "Disable autostart." << endl;

    TDEConfig *config = app.config();
    config->setGroup( "Startup" );
    config->writeEntry( "EnableAutostart", false );
  }

  convertDistributionLists();
}

