/*
    This file is part of Kontact.
    Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>
    Copyright (C) 2004 Reinhold Kainhofer <reinhold@kainhofer.com>

    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.

    As a special exception, permission is given to link this program
    with any edition of TQt, and distribute the resulting executable,
    without including the source code for TQt in the source distribution.
*/

#include <tqimage.h>
#include <tqlabel.h>
#include <tqlayout.h>
#include <tqtooltip.h>
#include <tqfile.h>
#include <tqlabel.h>
#include <tqtextedit.h>
#include <tqvbox.h>

#include <dcopclient.h>
#include <dcopref.h>
#include <tdeapplication.h>
#include <kdebug.h>
#include <tdeglobal.h>
#include <tdeglobalsettings.h>
#include <kiconloader.h>
#include <tdelocale.h>
#include <kurllabel.h>
#include <kdialogbase.h>
#include <tdemessagebox.h>

#include "pilotDaemonDCOP_stub.h"

#include <ktextedit.h>

#include "summarywidget.h"

SummaryWidget::SummaryWidget( TQWidget *parent, const char *name )
  : Kontact::Summary( parent, name ),
    DCOPObject( "KPilotSummaryWidget" ),
    mDCOPSuccess( false ),
    mStartedDaemon( false ),
    mShouldStopDaemon( true )
{
  mLayout = new TQGridLayout( this, 2, 3, 3, 3 );

  int row=0;
  TQPixmap icon = TDEGlobal::iconLoader()->loadIcon( "kpilot", TDEIcon::Desktop, TDEIcon::SizeMedium );
  TQWidget *header = createHeader( this, icon, i18n( "KPilot Configuration" ) );
  mLayout->addMultiCellWidget( header, row,row, 0,3 );

  // Last sync information
  row++;
  mSyncTimeTextLabel = new TQLabel( i18n( "<i>Last sync:</i>" ), this);
  mLayout->addWidget( mSyncTimeTextLabel, row, 0 );
  mSyncTimeLabel = new TQLabel( i18n( "No information available" ), this );
  mLayout->addWidget( mSyncTimeLabel, row, 1 );
  mShowSyncLogLabel = new KURLLabel( "", i18n( "[View Sync Log]" ), this );
  mLayout->addWidget( mShowSyncLogLabel, row, 3 );
  connect( mShowSyncLogLabel, TQ_SIGNAL( leftClickedURL( const TQString& ) ),
    this, TQ_SLOT( showSyncLog( const TQString& ) ) );

  // User
  row++;
  mPilotUserTextLabel = new TQLabel( i18n( "<i>User:</i>" ), this);
  mLayout->addWidget( mPilotUserTextLabel, row, 0);
  mPilotUserLabel = new TQLabel( i18n( "Unknown" ), this );
  mLayout->addMultiCellWidget( mPilotUserLabel, row, row, 1, 3 );

  // Device information
  row++;
  mPilotDeviceTextLabel = new TQLabel( i18n( "<i>Device:</i>" ), this);
  mLayout->addWidget( mPilotDeviceTextLabel, row, 0 );
  mPilotDeviceLabel = new TQLabel( i18n( "Unknown" ), this );
  mLayout->addMultiCellWidget( mPilotDeviceLabel, row, row, 1, 3 );

  // Status
  row++;
  mDaemonStatusTextLabel = new TQLabel( i18n( "<i>Status:</i>" ), this);
  mLayout->addWidget( mDaemonStatusTextLabel, row, 0 );
  mDaemonStatusLabel = new TQLabel( i18n( "No communication with the daemon possible" ), this );
  mLayout->addMultiCellWidget( mDaemonStatusLabel, row, row, 1, 3 );

  // Conduits:
  row++;
  mConduitsTextLabel = new TQLabel( i18n( "<i>Conduits:</i>" ), this );
  mConduitsTextLabel->setAlignment( AlignAuto | AlignTop | ExpandTabs );
  mLayout->addWidget( mConduitsTextLabel, row, 0 );
  mConduitsLabel = new TQLabel( i18n( "No information available" ), this );
  mConduitsLabel->setAlignment( mConduitsLabel->alignment() | TQt::WordBreak );
  mLayout->addMultiCellWidget( mConduitsLabel, row, row, 1, 3 );

  // widgets shown if kpilotDaemon is not running
  row++;
  mNoConnectionLabel = new TQLabel( i18n( "KPilot is currently not running." ), this );
  mLayout->addMultiCellWidget( mNoConnectionLabel, row, row, 1, 2 );
  mNoConnectionStartLabel = new KURLLabel( "", i18n( "[Start KPilot]" ), this );
  mLayout->addWidget( mNoConnectionStartLabel, row, 3 );
  connect( mNoConnectionStartLabel, TQ_SIGNAL( leftClickedURL( const TQString& ) ),
           this, TQ_SLOT( startKPilot() ) );

  if ( !kapp->dcopClient()->isApplicationRegistered( "kpilotDaemon" ) ) {
    startKPilot();
  }

  connectDCOPSignal( 0, 0, "kpilotDaemonStatusDetails(TQDateTime,TQString,TQStringList,TQString,TQString,TQString,bool)",
                     "receiveDaemonStatusDetails(TQDateTime,TQString,TQStringList,TQString,TQString,TQString,bool)", false );
	connect( kapp->dcopClient(), TQ_SIGNAL( applicationRemoved( const TQCString & ) ), TQ_SLOT( slotAppRemoved( const TQCString& ) ) );
}

SummaryWidget::~SummaryWidget()
{
  if ( mStartedDaemon && mShouldStopDaemon ) {
    PilotDaemonDCOP_stub dcopToDaemon( "kpilotDaemon", "KPilotDaemonIface" );
    dcopToDaemon.quitNow(); // ASYNC, always succeeds.
  }
}

TQStringList SummaryWidget::configModules() const
{
  TQStringList modules;
  modules << "kpilot_config.desktop";
  return modules;
}

void SummaryWidget::receiveDaemonStatusDetails(TQDateTime lastSyncTime, TQString status, TQStringList conduits, TQString logFileName, TQString userName, TQString pilotDevice, bool killOnExit )
{
  mDCOPSuccess = true;
  mLastSyncTime = lastSyncTime;
  mDaemonStatus = status;
  mConduits = conduits;
  mSyncLog = logFileName;
  mUserName = userName;
  mPilotDevice = pilotDevice;
  mShouldStopDaemon = killOnExit;
  updateView();
}

void SummaryWidget::updateView()
{
  if ( mDCOPSuccess ) {
    if ( mLastSyncTime.isValid() ) {
      mSyncTimeLabel->setText( mLastSyncTime.toString(TQt::LocalDate) );
    } else {
      mSyncTimeLabel->setText( i18n( "No information available" ) );
    }
    if ( !mSyncLog.isEmpty() ) {
      mShowSyncLogLabel->setEnabled( true );
      mShowSyncLogLabel->setURL( mSyncLog );
    } else {
      mShowSyncLogLabel->setEnabled( false );
    }
    mPilotUserLabel->setText( mUserName.isEmpty() ? i18n( "unknown" ) : mUserName );
    mPilotDeviceLabel->setText( mPilotDevice.isEmpty() ? i18n( "unknown" ) : mPilotDevice );
    mDaemonStatusLabel->setText( mDaemonStatus );
    mConduitsLabel->setText( mConduits.join( ", " ) );
  } else {
    mSyncTimeLabel->setText( i18n( "No information available (Daemon not running?)" ) );
    mShowSyncLogLabel->setEnabled( false );
    mPilotUserLabel->setText( i18n( "unknown" ) );
    mPilotDeviceLabel->setText( i18n( "unknown" ) );
    mDaemonStatusLabel->setText( i18n( "No communication with the daemon possible" ) );
    mConduitsLabel->setText( i18n( "No information available" ) );
  }

  mSyncTimeTextLabel->setShown( mDCOPSuccess );
  mSyncTimeLabel->setShown( mDCOPSuccess );
  mShowSyncLogLabel->setShown( mDCOPSuccess );
  mPilotUserTextLabel->setShown( mDCOPSuccess );
  mPilotUserLabel->setShown( mDCOPSuccess );
  mPilotDeviceTextLabel->setShown( mDCOPSuccess );
  mPilotDeviceLabel->setShown( mDCOPSuccess );
  mDaemonStatusTextLabel->setShown( mDCOPSuccess );
  mDaemonStatusLabel->setShown( mDCOPSuccess );
  mConduitsTextLabel->setShown( mDCOPSuccess );
  mConduitsLabel->setShown( mDCOPSuccess );
  mNoConnectionLabel->setShown( !mDCOPSuccess );
  mNoConnectionStartLabel->setShown( !mDCOPSuccess );
}

void SummaryWidget::showSyncLog( const TQString &filename )
{
  KDialogBase dlg( this, 0, true, TQString(), KDialogBase::Ok, KDialogBase::Ok );
  dlg.setCaption( i18n( "KPilot HotSync Log" ) );

  TQTextEdit *edit = new TQTextEdit( dlg.makeVBoxMainWidget() );
  edit->setReadOnly( true );

  TQFile f(filename);
  if ( !f.open( IO_ReadOnly ) ) {
    KMessageBox::error( this, i18n( "Unable to open Hotsync log %1." ).arg( filename ) );
    return;
  }

  TQTextStream s( &f );
  while ( !s.eof() )
    edit->append( s.readLine() );

  edit->moveCursor( TQTextEdit::MoveHome, false );

  f.close();

  dlg.setInitialSize( TQSize( 400, 350 ) );
  dlg.exec();
}

void SummaryWidget::startKPilot()
{
  TQString error;
  TQCString appID;
  if ( !TDEApplication::tdeinitExec( "kpilotDaemon", TQString( "--fail-silently" ) ) ) {
    kdDebug(5602) << "No service available..." << endl;
    mStartedDaemon = true;
  }
}

void SummaryWidget::slotAppRemoved( const TQCString & appId )
{
  if ( appId == "kpilotDaemon" )
  {
    mDCOPSuccess = false;
    updateView();
  }
}


#include "summarywidget.moc"

