/*
    This file is part of tdepim.

    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 "egroupwarewizard.h"
#include "egroupwareconfig.h"

#include "tderesources/egroupware/tdeabc_egroupwareprefs.h"
#include "tderesources/egroupware/tdeabc_resourcexmlrpc.h"
#include "tderesources/egroupware/kcal_egroupwareprefs.h"
#include "tderesources/egroupware/kcal_resourcexmlrpc.h"
#include "tderesources/egroupware/knotes_egroupwareprefs.h"
#include "tderesources/egroupware/knotes_resourcexmlrpc.h"

#include <libkcal/resourcecalendar.h>

#include <klineedit.h>
#include <tdelocale.h>
#include <tdemessagebox.h>

#include <tqcheckbox.h>
#include <tqlabel.h>
#include <tqlayout.h>
#include <tqwhatsthis.h>


static TQString createURL( const TQString &server, bool useSSL, const TQString &location )
{
  KURL url;

  if ( useSSL )
    url.setProtocol( "https" );
  else
    url.setProtocol( "http" );

  url.setHost( server );
  url.setPath( "/" + location );

  return url.url();
}

class CreateEGroupwareTdeabcResource : public TDEConfigPropagator::Change
{
  public:
    CreateEGroupwareTdeabcResource()
      : TDEConfigPropagator::Change( i18n("Create eGroupware Addressbook Resource") )
    {
    }

    void apply()
    {
      kdDebug() << "Create eGroupware Addressbook Resource" << endl;

      KRES::Manager<TDEABC::Resource> manager( "contact" );
      manager.readConfig();

      TQString url = createURL( EGroupwareConfig::self()->server(), EGroupwareConfig::self()->useSSLConnection(), EGroupwareConfig::self()->xmlrpc_location() );

      TDEABC::ResourceXMLRPC *resource = new TDEABC::ResourceXMLRPC( url, EGroupwareConfig::self()->domain(),
                                                                 EGroupwareConfig::self()->user(),
                                                                 EGroupwareConfig::self()->password() );
      resource->setResourceName( i18n( "eGroupware" ) );
      manager.add( resource );
      manager.writeConfig();
    }
};

// TODO: fix the i18n strings after freeze...
class ChangeEGroupwareTdeabcResource : public TDEConfigPropagator::Change
{
  public:
    ChangeEGroupwareTdeabcResource( const TQString &identifier )
      : TDEConfigPropagator::Change( i18n("Create eGroupware Addressbook Resource") ),
        mIdentifier( identifier )
    {
    }

    void apply()
    {
      kdDebug() << "Change eGroupware Addressbook Resource" << endl;

      KRES::Manager<TDEABC::Resource> manager( "contact" );
      manager.readConfig();

      KRES::Manager<TDEABC::Resource>::Iterator it;
      for ( it = manager.begin(); it != manager.end(); ++it ) {
        if ( (*it)->identifier() == mIdentifier ) {
          TDEABC::ResourceXMLRPC *resource = static_cast<TDEABC::ResourceXMLRPC*>( *it );

          resource->prefs()->setUrl( createURL( EGroupwareConfig::self()->server(),
          EGroupwareConfig::self()->useSSLConnection(), EGroupwareConfig::self()->xmlrpc_location() ) );
          resource->prefs()->setDomain( EGroupwareConfig::self()->domain() );
          resource->prefs()->setUser( EGroupwareConfig::self()->user() );
          resource->prefs()->setPassword( EGroupwareConfig::self()->password() );

          manager.change( resource );
          manager.writeConfig();
          return;
        }
      }
    }

  private:
    TQString mIdentifier;
};

class CreateEGroupwareKcalResource : public TDEConfigPropagator::Change
{
  public:
    CreateEGroupwareKcalResource()
      : TDEConfigPropagator::Change( i18n( "Create eGroupware Calendar Resource" ) )
    {
    }

    void apply()
    {
      kdDebug() << "Create eGroupware Calendar Resource" << endl;

      KCal::CalendarResourceManager manager( "calendar" );
      manager.readConfig();

      KCal::ResourceXMLRPC *resource = new KCal::ResourceXMLRPC();
      resource->setResourceName( i18n( "eGroupware" ) );
      resource->prefs()->setUrl( createURL( EGroupwareConfig::self()->server(), EGroupwareConfig::self()->useSSLConnection(), EGroupwareConfig::self()->xmlrpc_location() ) );
      resource->prefs()->setDomain( EGroupwareConfig::self()->domain() );
      resource->prefs()->setUser( EGroupwareConfig::self()->user() );
      resource->prefs()->setPassword( EGroupwareConfig::self()->password() );
      manager.add( resource );
      manager.writeConfig();
    }
};

class ChangeEGroupwareKcalResource : public TDEConfigPropagator::Change
{
  public:
    ChangeEGroupwareKcalResource( const TQString &identifier )
      : TDEConfigPropagator::Change( i18n( "Create eGroupware Calendar Resource" ) ),
        mIdentifier( identifier )
    {
    }

    void apply()
    {
      kdDebug() << "Change eGroupware Calendar Resource" << endl;

      KCal::CalendarResourceManager manager( "calendar" );
      manager.readConfig();

      KCal::CalendarResourceManager::Iterator it;
      for ( it = manager.begin(); it != manager.end(); ++it ) {
        if ( (*it)->identifier() == mIdentifier ) {
          KCal::ResourceXMLRPC *resource = static_cast<KCal::ResourceXMLRPC*>( *it );

          resource->prefs()->setUrl( createURL( EGroupwareConfig::self()->server(),
          EGroupwareConfig::self()->useSSLConnection(), EGroupwareConfig::self()->xmlrpc_location() ) );
          resource->prefs()->setDomain( EGroupwareConfig::self()->domain() );
          resource->prefs()->setUser( EGroupwareConfig::self()->user() );
          resource->prefs()->setPassword( EGroupwareConfig::self()->password() );

          manager.change( resource );
          manager.writeConfig();
          return;
        }
      }
    }

  private:
    TQString mIdentifier;
};

class CreateEGroupwareKnotesResource : public TDEConfigPropagator::Change
{
  public:
    CreateEGroupwareKnotesResource()
      : TDEConfigPropagator::Change( i18n("Create eGroupware Notes Resource") )
    {
    }

    void apply()
    {
      kdDebug() << "Create eGroupware notes Resource" << endl;

      KRES::Manager<ResourceNotes> manager( "notes" );
      manager.readConfig();

      TQString url = createURL( EGroupwareConfig::self()->server(), EGroupwareConfig::self()->useSSLConnection(), EGroupwareConfig::self()->xmlrpc_location() );

      KNotes::ResourceXMLRPC *resource = new KNotes::ResourceXMLRPC();
      resource->setResourceName( i18n( "eGroupware" ) );
      resource->prefs()->setUrl( createURL( EGroupwareConfig::self()->server(), EGroupwareConfig::self()->useSSLConnection(), EGroupwareConfig::self()->xmlrpc_location() ) );
      resource->prefs()->setDomain( EGroupwareConfig::self()->domain() );
      resource->prefs()->setUser( EGroupwareConfig::self()->user() );
      resource->prefs()->setPassword( EGroupwareConfig::self()->password() );
      manager.add( resource );
      manager.writeConfig();
    }
};

class ChangeEGroupwareKnotesResource : public TDEConfigPropagator::Change
{
  public:
    ChangeEGroupwareKnotesResource( const TQString &identifier )
      : TDEConfigPropagator::Change( i18n("Create eGroupware Notes Resource") ),
        mIdentifier( identifier )
    {
    }

    void apply()
    {
      kdDebug() << "Change eGroupware Notes Resource" << endl;

      KRES::Manager<ResourceNotes> manager( "notes" );
      manager.readConfig();

      KRES::Manager<ResourceNotes>::Iterator it;
      for ( it = manager.begin(); it != manager.end(); ++it ) {
        if ( (*it)->identifier() == mIdentifier ) {
          KNotes::ResourceXMLRPC *resource = static_cast<KNotes::ResourceXMLRPC*>( *it );

          resource->prefs()->setUrl( createURL( EGroupwareConfig::self()->server(),
          EGroupwareConfig::self()->useSSLConnection(), EGroupwareConfig::self()->xmlrpc_location() ) );
          resource->prefs()->setDomain( EGroupwareConfig::self()->domain() );
          resource->prefs()->setUser( EGroupwareConfig::self()->user() );
          resource->prefs()->setPassword( EGroupwareConfig::self()->password() );

          manager.change( resource );
          manager.writeConfig();
          return;
        }
      }
    }

  private:
    TQString mIdentifier;
};

class EGroupwarePropagator : public TDEConfigPropagator
{
  public:
    EGroupwarePropagator()
      : TDEConfigPropagator( EGroupwareConfig::self(), "egroupware.kcfg" )
    {
    }

  protected:
    void addCustomChanges( Change::List &changes )
    {
      KCal::CalendarResourceManager kcalManager( "calendar" );
      kcalManager.readConfig();
      KCal::CalendarResourceManager::Iterator kcalIt;
      for ( kcalIt = kcalManager.begin(); kcalIt != kcalManager.end(); ++kcalIt ) {
        if ( (*kcalIt)->type() == "xmlrpc" ) break;
      }
      if ( kcalIt == kcalManager.end() ) {
        changes.append( new CreateEGroupwareKcalResource );
      } else {
        changes.append( new ChangeEGroupwareKcalResource( (*kcalIt)->identifier() ) );
      }

      KRES::Manager<TDEABC::Resource> tdeabcManager( "contact" );
      tdeabcManager.readConfig();
      KRES::Manager<TDEABC::Resource>::Iterator tdeabcIt;
      for ( tdeabcIt = tdeabcManager.begin(); tdeabcIt != tdeabcManager.end(); ++tdeabcIt ) {
        if ( (*tdeabcIt)->type() == "xmlrpc" ) break;
      }
      if ( tdeabcIt == tdeabcManager.end() ) {
        changes.append( new CreateEGroupwareTdeabcResource );
      } else {
        changes.append( new ChangeEGroupwareTdeabcResource( (*tdeabcIt)->identifier() ) );
      }

      KRES::Manager<ResourceNotes> knotesManager( "notes" );
      knotesManager.readConfig();
      KRES::Manager<ResourceNotes>::Iterator knotesIt;
      for ( knotesIt = knotesManager.begin(); knotesIt != knotesManager.end(); ++knotesIt ) {
        if ( (*knotesIt)->type() == "xmlrpc" ) break;
      }
      if ( knotesIt == knotesManager.end() ) {
        changes.append( new CreateEGroupwareKnotesResource );
      } else {
        changes.append( new ChangeEGroupwareKnotesResource( (*knotesIt)->identifier() ) );
      }
    }
};

EGroupwareWizard::EGroupwareWizard() : TDEConfigWizard( new EGroupwarePropagator )
{
  TQFrame *page = createWizardPage( i18n( "eGroupware Server" ) );

  TQGridLayout *topLayout = new TQGridLayout( page );
  topLayout->setSpacing( spacingHint() );

  TQLabel *label = new TQLabel( i18n( "&Server name:" ), page );
  topLayout->addWidget( label, 0, 0 );
  mServerEdit = new KLineEdit( page );
  label->setBuddy( mServerEdit );
  topLayout->addWidget( mServerEdit, 0, 1 );

  label = new TQLabel( i18n( "&Domain name:" ), page );
  topLayout->addWidget( label, 1, 0 );
  mDomainEdit = new KLineEdit( page );
  label->setBuddy( mDomainEdit );
  topLayout->addWidget( mDomainEdit, 1, 1 );

  label = new TQLabel( i18n( "&Username:" ), page );
  topLayout->addWidget( label, 2, 0 );
  mUserEdit = new KLineEdit( page );
  label->setBuddy( mUserEdit );
  topLayout->addWidget( mUserEdit, 2, 1 );

  label = new TQLabel( i18n( "&Password:" ), page );
  topLayout->addWidget( label, 3, 0 );
  mPasswordEdit = new KLineEdit( page );
  mPasswordEdit->setEchoMode( KLineEdit::Password );
  label->setBuddy( mPasswordEdit );
  topLayout->addWidget( mPasswordEdit, 3, 1 );

  label = new TQLabel( i18n( "&Location xmlrpc.php on server:" ), page );
  topLayout->addWidget( label, 4, 0 );
  mXMLRPC = new KLineEdit( page );
  mXMLRPC->setMinimumWidth( 175 );
  label->setBuddy( mXMLRPC );
  topLayout->addWidget( mXMLRPC, 4, 1 );
  TQWhatsThis::add( label, i18n( "Some servers may not have the xmlrpc.php file in the 'egroupware' folder of the server. With this option it is possible to eventually change the path to that file. For most servers, the default value is OK." ) );

  mUseSSLConnectionCheck = new TQCheckBox( i18n( "Use SS&L connection" ), page );
  topLayout->addMultiCellWidget( mUseSSLConnectionCheck, 5, 5, 0, 1 );

  topLayout->setRowStretch( 6, 1 );

  setupRulesPage();
  setupChangesPage();

  resize( sizeHint() );
}

EGroupwareWizard::~EGroupwareWizard()
{
}

TQString EGroupwareWizard::validate()
{
  if( !mXMLRPC->text().endsWith( "xmlrpc.php" ) )
    return i18n( "Invalid path to xmlrpc.php entered." );

  if( mServerEdit->text().isEmpty() ||
      mDomainEdit->text().isEmpty() ||
      mUserEdit->text().isEmpty() ||
      mPasswordEdit->text().isEmpty() ||
      mXMLRPC->text().isEmpty() )
    return i18n( "Please fill in all fields." );

  return TQString();
}

void EGroupwareWizard::usrReadConfig()
{
  mServerEdit->setText( EGroupwareConfig::self()->server() );
  mDomainEdit->setText( EGroupwareConfig::self()->domain() );
  mUserEdit->setText( EGroupwareConfig::self()->user() );
  mPasswordEdit->setText( EGroupwareConfig::self()->password() );
  mXMLRPC->setText( EGroupwareConfig::self()->xmlrpc_location() );
  mUseSSLConnectionCheck->setChecked( EGroupwareConfig::self()->useSSLConnection() );
}

void EGroupwareWizard::usrWriteConfig()
{
  EGroupwareConfig::self()->setServer( mServerEdit->text() );
  EGroupwareConfig::self()->setDomain( mDomainEdit->text() );
  EGroupwareConfig::self()->setUser( mUserEdit->text() );
  EGroupwareConfig::self()->setPassword( mPasswordEdit->text() );
  EGroupwareConfig::self()->setXmlrpc_location( mXMLRPC->text() );
  EGroupwareConfig::self()->setUseSSLConnection( mUseSSLConnectionCheck->isChecked() );
}
