/***************************************************************************
    smb4khomesshareshandler  -  This class handles the homes shares.
                             -------------------
    begin                : Do Aug 10 2006
    copyright            : (C) 2006 by Alexander Reinholdt
    email                : dustpuppy@mail.berlios.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 Street, Fifth Floor, Boston,   *
 *   MA  02110-1301 USA                                                    *
 ***************************************************************************/

// TQt includes
#include <tqmap.h>
#include <tqlayout.h>
#include <tqlabel.h>
#include <tqfile.h>

// KDE includes
#include <kdebug.h>
#include <kstandarddirs.h>
#include <tdelocale.h>
#include <kiconloader.h>
#include <kcombobox.h>

// application specific includes
#include "smb4khomesshareshandler.h"
#include "smb4kdefs.h"
#include "smb4kerror.h"


Smb4KHomesSharesHandler::Smb4KHomesSharesHandler( TQObject *parent, const char *name )
: TQObject( parent, name )
{
  // First we need the directory.
  TDEStandardDirs *stddir = new TDEStandardDirs();
  TQString dir = locateLocal( "data", "smb4k", TDEGlobal::instance() );

  if ( !stddir->exists( dir ) )
  {
    stddir->makeDir( dir );
  }

  delete stddir;

  m_dlg = NULL;
}


Smb4KHomesSharesHandler::~Smb4KHomesSharesHandler()
{
  delete m_dlg;
}


const TQString Smb4KHomesSharesHandler::specifyUser( const TQString &host, TQWidget *parent, const char *name )
{
  TQString username = TQString();

  m_dlg = new KDialogBase( KDialogBase::Plain, i18n( "Specify User" ), KDialogBase::User1|KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok, parent, name, true, true );
  m_dlg->setButtonGuiItem( KDialogBase::User1, KGuiItem( i18n( "Clear List" ), "edit-delete", 0, 0 ) );
  m_dlg->enableButton( KDialogBase::Ok, false );
  m_dlg->enableButton( KDialogBase::User1, false );

  // Set up the ask pass dialog.
  TQFrame *frame = m_dlg->plainPage();
  TQGridLayout *layout = new TQGridLayout( frame );
  layout->setSpacing( 5 );

  TQLabel *pic = new TQLabel( frame );
  pic->setPixmap( DesktopIcon( "preferences-desktop-personal" ) );
  pic->setMargin( 10 );

  TQLabel *text = new TQLabel( i18n( "Please specify a user name." ), frame );

  TQLabel *userLabel = new TQLabel( i18n( "User:" ), frame );
  KComboBox *userCombo = new KComboBox( true, frame, "UserComboBox" );
  userCombo->setDuplicatesEnabled( false );

  TQSpacerItem *spacer1 = new TQSpacerItem( 10, 10, TQSizePolicy::Expanding, TQSizePolicy::Preferred );

  layout->addWidget( pic, 0, 0, 0 );
  layout->addMultiCellWidget( text, 0, 0, 1, 3, 0 );
  layout->addWidget( userLabel, 1, 0, 0 );
  layout->addMultiCellWidget( userCombo, 1, 1, 1, 4, 0 );
  layout->addItem( spacer1, 0, 2 );

  connect( userCombo, TQT_SIGNAL( textChanged( const TQString &) ),
           this,      TQT_SLOT( slotTextChanged( const TQString & ) ) );
  connect( m_dlg,     TQT_SIGNAL( user1Clicked() ),
           this,      TQT_SLOT( slotClearClicked() ) );

  // Read the list of logins, that are already defined
  // for this 'homes' share.
  TQStringList list = read_names( host );

  if ( !list.isEmpty() )
  {
    userCombo->insertStringList( list, -1 );
    m_dlg->enableButton( KDialogBase::User1, true );
  }

  userCombo->setCurrentText( TQString() );

  // Do the last things before showing.
  userCombo->setFocus();
  m_dlg->setFixedSize( m_dlg->sizeHint() );

  if ( m_dlg->exec() == KDialogBase::Accepted )
  {
    // First make sure, the list is cleared:
    list.clear();

    // Write the new list of logins to the config file.
    if ( !userCombo->lineEdit()->text().isEmpty() )
    {
      list.append( userCombo->lineEdit()->text() );
    }

    int index = 0;

    while ( index < userCombo->count() )
    {
      if ( list.find( userCombo->text( index ) ) == list.end() )
      {
        list.append( userCombo->text( index ) );
      }

      index++;
    }

    list.sort();

    write_names( host, list );

    username = userCombo->currentText();
  }

  delete m_dlg;
  m_dlg = NULL;

  return username;
}


const TQStringList &Smb4KHomesSharesHandler::read_names( const TQString &host )
{
  // Clear the old contents of this list:
  m_names.clear();

  TQFile file( locateLocal( "data", "smb4k/homes_shares", TDEGlobal::instance() ) );

  if ( file.open( IO_ReadOnly ) )
  {
    TQTextStream ts( &file );
    ts.setEncoding( TQTextStream::Locale );

    TQString line;
    bool get_names = false;

    while ( !ts.atEnd() )
    {
      line = ts.readLine();

      if ( !get_names )
      {
        if ( TQString::compare( line.stripWhiteSpace(), "["+host.upper()+"]" ) == 0 )
        {
          // Found the host:
          get_names = true;

          continue;
        }
        else
        {
          // No match yet...
          continue;
        }
      }
      else
      {
        if ( !line.stripWhiteSpace().isEmpty() )
        {
          // Write the names to the list:
          m_names = TQStringList::split( ",", line, false );

          // This is not needed, but let's do it anyway:
          get_names = false;

          break;
        }
      }
    }

    file.close();
  }
  else
  {
    if ( file.exists() )
    {
      Smb4KError::error( ERROR_READING_FILE, file.name() );

      // The list is empty:
      return m_names;
    }
  }

  return m_names;
}


void Smb4KHomesSharesHandler::write_names( const TQString &host, const TQStringList &names )
{
  // First get the whole contents of the file, so that
  // we can easily modify it:
  TQStringList contents;

  TQFile file( locateLocal( "data", "smb4k/homes_shares", TDEGlobal::instance() ) );

  if ( file.open( IO_ReadOnly ) )
  {
    TQTextStream ts( &file );
    ts.setEncoding( TQTextStream::Locale );

    contents = TQStringList::split( '\n', ts.read(), true );

    file.close();
  }
  else
  {
    if ( file.exists() )
    {
      Smb4KError::error( ERROR_READING_FILE, file.name() );

      return;
    }
  }

  // Now search for the host:
  TQStringList::Iterator it;

  for ( it = contents.begin(); it != contents.end(); ++it )
  {
    if ( TQString::compare( (*it).stripWhiteSpace().upper(), "["+host.upper()+"]" ) == 0 )
    {
      if ( !names.isEmpty() )
      {
        // Move to the line with the names:
        it++;
        // Change the line:
        *it = names.join( "," );
      }
      else
      {
        // Remove the host entry:
        it = contents.remove( it );
        // Remove the user names:
        it = contents.remove( it );

        // Remove the blank line following the entry:
        if ( it != contents.end() && (*it).stripWhiteSpace().isEmpty() )
        {
          contents.remove( it );
        }
      }

      break;
    }
    else
    {
      continue;
    }
  }

  // If we haven't found the host, append it to the end:
  if ( it == contents.end() )
  {
    if ( !contents.isEmpty() )
    {
      contents.append( "" );
    }

    contents.append( "["+host.upper()+"]");
    contents.append( names.join( "," ) );
  }


  // Now write or remove the file:
  if ( !contents.isEmpty() )
  {
    if ( file.open( IO_WriteOnly ) )
    {
      TQTextStream ts( &file );
      ts.setEncoding( TQTextStream::Locale );

      ts << contents.join( "\n" );

      file.close();
    }
    else
    {
      Smb4KError::error( ERROR_WRITING_FILE, file.name() );

      return;
    }
  }
  else
  {
    file.remove();
  }
}


/////////////////////////////////////////////////////////////////////////////
// TQT_SLOT IMPLEMENTATIONS
/////////////////////////////////////////////////////////////////////////////

void Smb4KHomesSharesHandler::slotTextChanged( const TQString &text )
{
  if ( !text.isEmpty() )
  {
    m_dlg->enableButtonOK( true );
  }
  else
  {
    m_dlg->enableButtonOK( false );
  }
}


void Smb4KHomesSharesHandler::slotClearClicked()
{
  if ( m_dlg )
  {
    KComboBox *cb = (KComboBox *)m_dlg->child( "UserComboBox", "KComboBox", true );

    if ( cb )
    {
      cb->clearEdit();
      cb->clear();

      m_dlg->enableButton( KDialogBase::User1, false );
    }
  }
}

#include "smb4khomesshareshandler.moc"

