/***************************************************************************
 *   Copyright (C) 2004 by Judd Baileys                                    *
 *   jbaileys@bigpond.net.au                                               *
 *                                                                         *
 *   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.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#define EVERYTHING_OK 1
#define ERROR_OPENING_PAPSECRETS_FOR_READ -1
#define ERROR_OPENING_PAPSECRETS_FOR_WRITE -2
#define ERROR_OPENING_CHAPSECRETS_FOR_READ -3
#define ERROR_OPENING_CHAPSECRETS_FOR_WRITE -4

#define ERROR_OPENING_OPTIONS_FOR_WRITE -5
#define ERROR_OPENING_OPTIONS_FOR_READ -6
#define PPPSETTINGSDIR "/etc/ppp/kdsl/"
#define OPTIONSPATH "/etc/ppp/kdsl/conf."
#define PPPOEPATH "/etc/ppp/kdsl/options."
#define log_file "/etc/ppp/kdsl/kdsl.log"

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include <qbuttongroup.h>
#include <karchive.h>
#include <ktar.h>
// #include <kurlrequesterdlg.h>
#include <kmessagebox.h>
#include <klineedit.h>
#include <kpushbutton.h>    // for KPushButton
#include <klocale.h>        // for i18n()
#include <kiconloader.h>    // for KIconLoader
#include <kglobal.h>        // for KGlobal
#include <klistbox.h>
#include <klocale.h>
#include <qgroupbox.h>
#include <knuminput.h>
#include <kapp.h>
#include <kstandarddirs.h>
#include <qradiobutton.h>
#include <kpassdlg.h>

// QT Includes
#include <qlayout.h>        // for QVBoxLayout
#include <qlabel.h>         // for QLabel
#include <qframe.h>         // for QFrame
#include <qcombobox.h>
#include <qslider.h>
#include <qfile.h>
#include <qdir.h>
#include <qtextstream.h>
#include <qregexp.h>
#include <qstring.h>

 #include "pppstats.h"
 #include "docbrowser.h"
 #include "aboutdlg.h"
 #include "preftheme.h"
 #include "prefadvanced.h"
#include "prefgeneral.h"    // class PrefGeneral
#include "prefdialog.h"
#include "prefdialog.moc"
// #include "kdsl.h"
  #include "configuration.h"
// #include <kfiledialog.h>
#include <knotifyclient.h>
#include <kio/job.h>
#include <kio/netaccess.h>
#include <karchive.h>
#include <ktar.h>
#include <dcopclient.h>
// #include "docking.h"
#include <ktextbrowser.h>
#include <qiconview.h>
#include <qpushbutton.h>
#include <qlistview.h>
#include <kcolordialog.h>


 extern kdsl *m_kdsl;
 extern DockWidget *dock_widget;
 extern PPPStats* stats;
 
 QString ethDevice;
 QString dslEth;
 QString modemDev; 
 QString flowControl;
 QString speedControl;
 QString modemVolume;
 
 PrefDialog::PrefDialog(QWidget *parent, const char *name)
 : KDialogBase(IconList, i18n("Preferences"), Ok|Apply|Cancel, Apply , parent, name)
{

// Default Arguements for configuration files

	ethDevice="eth0";
	if(gpppdata.modemDevice()==""){
	modemDev="/dev/modem";
	}
	else
	{
	modemDev=(gpppdata.modemDevice());
	}
	
	if(gpppdata.storedEthDevice().isEmpty()){
	ethDevice="eth0";
	dslEth="eth0";
	}
	else
	{
	ethDevice=(gpppdata.storedEthDevice());
	dslEth=(gpppdata.storedEthDevice());
	}
	
	if(gpppdata.flowControl().isEmpty() )
	flowControl="crtscts";
	else
	flowControl=(gpppdata.flowControl());
	
	if(gpppdata.speedControl().isEmpty() )
	speedControl="57600";
	else
	speedControl=(gpppdata.speedControl());
	gpppdata.save();
	
	
	
	
      QFrame *frame;
      QGridLayout *frameLayout;
//	filterApply == "none";

      frame = addPage(i18n("Accounts"), i18n("Account options"),
      KGlobal::iconLoader()->loadIcon("password",KIcon::Panel,0,false) );
      frameLayout = new QGridLayout( frame, 0, 0, 0 );
      m_prefGeneral = new PrefGeneral(frame);
      m_prefGeneral->pluginButton->setPixmap( SmallIcon( "folder_yellow") ) ;
      m_prefGeneral->accountIconButton->setPixmap( SmallIcon( "folder_red") ) ;
      m_prefGeneral->dialupAccountIconButton->setPixmap( SmallIcon( "folder_yellow") ) ;
      m_prefGeneral->dialupAccountIconButton_2->setPixmap( SmallIcon( "folder_yellow") ) ;
      m_prefGeneral->pixmapLabel2->setPixmap( UserIcon ("internetbrowser.png") );
      m_prefGeneral->pixmapLabel2_2->setPixmap( UserIcon ("internetbrowser.png") );      
      frameLayout->addWidget(m_prefGeneral,0 ,0 ,0);

	frame = addPage(i18n("Preferences"), i18n("Kdsl Preferences"),
        KGlobal::iconLoader()->loadIcon("package_utilities",KIcon::Panel,0,false) );
	frameLayout = new QGridLayout( frame, 0, 0, 0)  ;
        m_prefAdvanced = new PrefAdvanced(frame);
        frameLayout->addWidget(m_prefAdvanced, 0, 0, 0);

	
	frame = addPage(i18n("Dock Icon Themes"), i18n("Icon Themes"),
        KGlobal::iconLoader()->loadIcon("package_graphics",KIcon::Panel,0,false) );
	frameLayout = new QGridLayout( frame, 0, 0, 0 );
        m_prefTheme = new PrefTheme(frame);
        frameLayout->addWidget(m_prefTheme,0 ,0, 0);	  
            
 // We've disabled this for the moment until we add full support for ISDN connections.  Hopefully will be implemented in version 0.6
   m_prefGeneral->isdnRadioButton->setEnabled(FALSE);   

//    m_prefGeneral->kIntNumInput1->setValue( gpppdata.pppdTimeout() );
    resize( QSize(500, 200).expandedTo(minimumSizeHint()) );
  
 // adding the Broswer Documentation Page
        frame = addPage(i18n("Help & Documentation"), i18n("Help & Documentation"),
	KGlobal::iconLoader()->loadIcon("help_index",KIcon::Panel,0,false) );
	frameLayout = new QGridLayout (frame,0, 0, 0 );
	browser = new DocBrowser(frame);
	frameLayout->addWidget(browser,0 ,0 ,0);
	browser->resize(500,500);   
    
     connect( m_prefGeneral->pluginButton, SIGNAL(clicked()), this, SLOT (newPlugin() ) );     
     connect(m_prefGeneral->accountIconButton, SIGNAL(clicked()), this, SLOT (newAccountIcon() ) );   
     connect(m_prefGeneral->dialupAccountIconButton, SIGNAL(clicked()), this, SLOT (newAccountIcon() ) );      
     connect(m_prefGeneral->dialupAccountIconButton_2,   SIGNAL(clicked()), this, SLOT (newAccountIcon() ) ); 
     connect(m_prefGeneral->dslRadioButton, SIGNAL(clicked()), this, SLOT(newDslAccount()) );
     connect(m_prefGeneral->dialupRadioButton, SIGNAL(clicked()), this, SLOT(newDialupAccount()) );
     connect(m_prefGeneral->accountlist_1, SIGNAL(executed(QIconViewItem *)), this, SLOT (editAccount(QIconViewItem *)) );
     connect( m_prefGeneral->usbCheckBox, SIGNAL(toggled(bool)), this, SLOT(dslAccounts()) );   
     connect( m_prefTheme->newThemeButton, SIGNAL(clicked()), this, SLOT (newTheme() ) );
     connect( m_prefTheme->themeListBox, SIGNAL(highlighted(int)), this, SLOT (themeListBoxSelect(int)) );
     connect( m_prefTheme->themeListBox, SIGNAL(selected(int)), this, SLOT (newDefaultTheme(int)) );
     connect( m_prefTheme->deleteThemeButton, SIGNAL( clicked()), SLOT( deletetheme()));    
     connect(m_prefGeneral->accountlist_1, SIGNAL(rightButtonClicked(QIconViewItem *, const QPoint & )), this, SLOT (deleteAccount(QIconViewItem*)) );
     connect( m_prefGeneral->ethernetComboBox, SIGNAL(activated(int)),this, SLOT (comboBoxItemActivated(int)) );
     connect( m_prefGeneral->dialupModemComboBox, SIGNAL(activated(int)),this, SLOT (dialupComboBoxItemActivated(int)) );
     connect(m_prefGeneral->flowControlComboBox, SIGNAL(activated(int)),this, SLOT (flowComboBoxItemActivated(int)) );
     connect(m_prefGeneral->dialupSpeedComboBox, SIGNAL(activated(int)),this, SLOT (modemSpeedComboBoxItemActivated(int)) );
     connect(m_prefGeneral->modemVolumeSlider, SIGNAL(valueChanged(int)),this, SLOT (modemVolumeActivated(int )) );
     connect(this, SIGNAL(taskApply()), m_prefAdvanced, SLOT (applyTask()) );     

     if(gpppdata.defaultTheme().isEmpty()) {
        m_prefTheme->currentThemeTextLabel->setText("kdsl");
	gpppdata.setThemename("kdsl");
	gpppdata.save();
     }
        
     if(gpppdata.storeEnableNotify()==0) {
     m_prefAdvanced->disableNotifyCheckBox->setChecked(FALSE);
     }
     else {
     m_prefAdvanced->disableNotifyCheckBox->setChecked(TRUE);     
     }   
     
  if(gpppdata.storeEnableSound()==0) {
     m_prefAdvanced->soundCheckBox->setChecked(FALSE);
     }
     else {
     m_prefAdvanced->soundCheckBox->setChecked(TRUE);     
     }
     
  if(gpppdata.storeHideIP()==0) {
     m_prefAdvanced->showIPCheckBox->setChecked(FALSE);
     }
     else {
      m_prefAdvanced->showIPCheckBox->setChecked(TRUE);    
      }
  if(gpppdata.storeAutostart()==0) {
     m_prefAdvanced->kdeStartupCheckBox-> setChecked(FALSE);
     }
     else {
       m_prefAdvanced->kdeStartupCheckBox->setChecked(TRUE);   
     }
  if(gpppdata.storeConnect()==0) {
     m_prefAdvanced->startupCheckBox->setChecked(FALSE);
     }
     else {
      m_prefAdvanced->startupCheckBox->setChecked(TRUE);
     }    
 
   if(gpppdata.storeClock()==0) {
     m_prefAdvanced->timeCheckBox->setChecked(FALSE);
     }
     else {
      m_prefAdvanced->timeCheckBox->setChecked(TRUE);
     }      
    
     m_prefTheme->currentThemeTextLabel->setText(gpppdata.themename());         
     if(gpppdata.themename().isEmpty()) {
      m_prefTheme->currentThemeTextLabel->setText("kdsl");
   m_prefTheme->themeLineEdit->setText("kdsl");
        gpppdata.setThemename(m_prefTheme->themeLineEdit->text());
	QString themedir;
	themedir = gpppdata.themename();
	QString both = themedir + "/dock_left.png";
	dockicon = UserIcon (both);
	m_prefTheme->themeListBox->insertItem(dockicon, gpppdata.themename() );
	}

    if(gpppdata.count() > 0) {
    for(int i=0; i <= gpppdata.count()-1; i++) {
      gpppdata.setAccountbyIndex(i);
          KStandardDirs *dirs = KGlobal::dirs();
  	  QString themePath;

	  if(gpppdata.accountIconName()=="")
	  	  themePath = dirs->findResource ("data", "kdsl/pics/folder_red_open.png");     
	else
	themePath = gpppdata.accountIconName();

          (void) new QIconViewItem( m_prefGeneral->accountlist_1, ( gpppdata.accname()), themePath  );
    }
  }

    if(gpppdata.themecount() > 0) {
    for(int i=0; i <= gpppdata.themecount()-1; i++) {
        gpppdata.setThemebyIndex(i);
	QString themedir;
	themedir = gpppdata.themename();
	QString both = themedir + "/dock_left.png";
	dockicon = UserIcon (both);
	m_prefTheme->themeListBox->insertItem(dockicon, gpppdata.themename() );
    }
 }

    if(gpppdata.themecount() < 1) {
    setStartTheme();
    }
    
 	if(getuid()!=0){
	m_prefGeneral->accountlist_1->setEnabled(FALSE);
	m_prefGeneral->dslRadioButton->setEnabled(FALSE);
	m_prefGeneral->isdnRadioButton->setEnabled(FALSE);
	m_prefGeneral->dialupRadioButton->setEnabled(FALSE);
        m_prefGeneral->widgetStack3->raiseWidget(3);      
	}   
	else
	m_prefGeneral->accountlist_1->setEnabled(TRUE);	
        themeListBoxSelect(m_prefTheme->themeListBox->currentItem());
}  
 
void PrefDialog::newDialupAccount()
{
filterApply = "dialupNewEnabled";
m_prefGeneral->dialupHeaderTextLabel->setText(i18n("<b><font color=\"#e5ff4f\" face=\"helvetica [Adobe]\"><h2>Creating a new account </h2></font></b>"));
m_prefGeneral->widgetStack3->raiseWidget(2);
m_prefGeneral->dialupAccountIconLineEdit->clear();
m_prefGeneral->dialupConnectionNameLineEdit->clear();
m_prefGeneral->dialupPasswordLineEdit->clear();
m_prefGeneral->dialupPhoneLineEdit->clear();
m_prefGeneral->dialupUsernameLineEdit->clear();
dialupAccounts();
}

void PrefDialog::deleteAccount(QIconViewItem * item)
{
// We experiences crashes if we accidentally right click on an area of the Connections Window that does not contain an icon.  So we work
//around it like this:
// m_prefGeneral->widgetStack3->raiseWidget(0);
if(!item)
return;

//Now back to normal

  QString s = i18n("Are you sure you want to delete\nthe account \"%1\"?").arg(item->text()) ;
  if(KMessageBox::warningYesNo(this, s, i18n("Confirm Delete")) != KMessageBox::Yes) {
  this->slotCancel();
  return;
   }
   QString Account;
   Account = PPPOEPATH + item->text();
   QFile da;
   da.remove(Account);  
   if(gpppdata.deleteAccount(item->text() ))
   m_prefGeneral->accountlist_1->takeItem(item );
  emit resetaccounts();
  gpppdata.save(); 
  m_prefGeneral->accountlist_1->clear();
    if(gpppdata.count() > 0) {
    for(int i=0; i <= gpppdata.count()-1; i++) {
        KStandardDirs *dirs = KGlobal::dirs();
      gpppdata.setAccountbyIndex(i);
	QString themePath;
 	  if(gpppdata.accountIconName()=="")
	  	  themePath = dirs->findResource ("data", "kdsl/pics/folder_red_open.png");     
	else
	themePath = gpppdata.accountIconName();

          (void) new QIconViewItem( m_prefGeneral->accountlist_1, ( gpppdata.accname()), themePath  );     

    }
  }
	QString deletePath="/etc/ppp/kdsl/delete.Accounts";
	QString accountdelete;
	accountdelete=item->text();
	QFile file(deletePath);
        QTextStream stream( &file );		
	if ( file.open( (IO_WriteOnly | IO_Append) ) ) {
	stream << accountdelete;

	}
	file.close();
}	 


void PrefDialog::newPlugin() {
	QString plugs = KFileDialog::getOpenFileName("/usr/lib/pppd/2.4.*/", "*.so |Shared Objects (*.so)", this);
   if (plugs != NULL) m_prefGeneral->pluginLineEdit->setText(plugs);
  }
  
void PrefDialog::newAccountIcon()
{
	QString plugs = KFileDialog::getOpenFileName("/", "*.png *.jpg | Image Files ", this);
	if(filterApply == "dslNewEnabled")
   if (plugs != NULL) m_prefGeneral->accountIconLineEdit->setText(plugs);
   if(filterApply == "dslEnabled")
   if (plugs != NULL) m_prefGeneral->accountIconLineEdit->setText(plugs);   
   if(filterApply == "dialupNewEnabled")     
   if (plugs != NULL) m_prefGeneral->dialupAccountIconLineEdit->setText(plugs);	 
   if(filterApply == "dialupEnabled")     
   if (plugs != NULL) m_prefGeneral->dialupAccountIconLineEdit->setText(plugs);	 	
   if(filterApply == "nonRoot")
   if (plugs != NULL) m_prefGeneral->dialupAccountIconLineEdit_2->setText(plugs); 
}

void PrefDialog::newDslAccount()
{
filterApply = "dslNewEnabled";								// #00aaff
     m_prefGeneral->headerTextLabel->setText(i18n("<b><font color=\"#e5ff4f\" face=\"helvetica [Adobe]\"><h2>Creating a new account </h2></font></b>"));
m_prefGeneral->widgetStack3->raiseWidget(1);
dslAccounts();
m_prefGeneral->connectionNameLineEdit->setEnabled(TRUE);
m_prefGeneral->connectionNameLineEdit->clear();
m_prefGeneral->usernameLineEdit->clear();
m_prefGeneral->passwordLineEdit->clear();
m_prefGeneral->networkLineEdit->clear();
m_prefGeneral->checkBox4->setChecked(TRUE);
m_prefGeneral->dnsRadioButton->setChecked(TRUE);
m_prefGeneral->usbCheckBox->setChecked(true);
m_prefGeneral->accountIconLineEdit->clear();

}
  
 void PrefDialog::modems() 
{
                m_prefGeneral->ethernetComboBox->clear();
    		 if(m_prefGeneral->dslRadioButton->isChecked()) {
     		   m_prefGeneral->ethernetComboBox->insertItem("eth0");
     		   m_prefGeneral->ethernetComboBox->insertItem("eth1");
     		   m_prefGeneral->ethernetComboBox->insertItem("eth2");
     		   m_prefGeneral->ethernetComboBox->insertItem("eth3");	
		    if(m_prefGeneral->usbCheckBox->isChecked()) {
		    
     		    m_prefGeneral->ethernetComboBox->insertItem("nas0");
     		    m_prefGeneral->ethernetComboBox->insertItem("tap0");	
		    }							
	}
     if(m_prefGeneral->isdnRadioButton->isChecked()) {	
     }
     
     if(m_prefGeneral->dialupRadioButton->isChecked()) {	
      		m_prefGeneral->dialupModemComboBox->insertItem("/dev/modem");
     		m_prefGeneral->dialupModemComboBox->insertItem("/dev/ttyS0");
     		m_prefGeneral->dialupModemComboBox->insertItem("/dev/ttyS1");
     		m_prefGeneral->dialupModemComboBox->insertItem("/dev/ttyS2");	    
     		m_prefGeneral->dialupModemComboBox->insertItem("/dev/ttyS3");		
	}
		
}


       
PrefDialog::~PrefDialog()
{
}

void PrefDialog::editAccount(QIconViewItem *item)
{
    m_prefAdvanced->showIPCheckBox->setChecked(gpppdata.storeHideIP());
    m_prefAdvanced->kdeStartupCheckBox->setChecked(gpppdata.storeAutostart());
    m_prefAdvanced->startupCheckBox->setChecked(gpppdata.storeConnect());    
    m_prefAdvanced->timeCheckBox->setChecked(gpppdata.storeClock());
    m_prefGeneral->checkBox4->setChecked(gpppdata.storeUsePlugin());
    m_prefAdvanced->soundCheckBox->setChecked(gpppdata.storeEnableSound());
    m_prefAdvanced->disableNotifyCheckBox->setChecked(gpppdata.storeEnableNotify());
    if(getuid()==0)
    {
     m_prefGeneral->widgetStack3->raiseWidget(1);
     gpppdata.setAccount(item->text());
     if (gpppdata.storedAccType()=="DSL") {
         filterApply = "dslEnabled";
         m_prefGeneral->widgetStack3->raiseWidget(1);
	dslAccounts();
	item->setPixmap(gpppdata.accountIconName());
     m_prefGeneral->headerTextLabel->setText(i18n("<b><font color=\"#00aaff\" face=\"helvetica [Adobe]\"><h2>Making changes to %1</h2></font></b>").arg(gpppdata.accname()) );
     m_prefGeneral->accountlist_1->setEnabled(FALSE);
     m_prefGeneral->connectionNameLineEdit->setText(gpppdata.accname());
     m_prefGeneral->connectionNameLineEdit->setEnabled(FALSE);
     m_prefGeneral->nonRootCheckBox->setChecked(gpppdata.storeEnableRoot());
     m_prefGeneral->usernameLineEdit->setText(gpppdata.storedUsername());
     m_prefGeneral->passwordLineEdit->setText(gpppdata.storedPassword());
     m_prefGeneral->store_password->setChecked(gpppdata.storePassword());
     m_prefGeneral->ethernetComboBox->setCurrentItem(gpppdata.storedEthDevice());     
     m_prefGeneral->store_password->setChecked(gpppdata.storePassword());
     if(gpppdata.autoDNS()==1)
     m_prefGeneral->dnsRadioButton->setChecked(TRUE);
     else
     m_prefGeneral->dnsRadioButton->setChecked(FALSE);     
     m_prefGeneral->accountIconLineEdit->setText(gpppdata.accountIconName());
     m_prefGeneral->kIntNumInput1->setValue( gpppdata.pppdTimeout() );
     m_prefGeneral->usbCheckBox->setChecked(gpppdata.get_usb());
     
     if(gpppdata.storeUsage()==1) {
     m_prefGeneral->usageCheckBox->setChecked(gpppdata.storeUsage());
     m_prefGeneral->usageLineEdit->setText(gpppdata.usageURL());
         if (gpppdata.storeBrowserUsage()==1) {
	    m_prefGeneral->externalBrowserCheckBox->setChecked(gpppdata.storeBrowserUsage());
	    m_prefGeneral->browserLineEdit->setText(gpppdata.browserURL());
	 }
     }
 
     if (gpppdata.storeUsePlugin()) {
     	m_prefGeneral->checkBox4->setChecked(gpppdata.storeUsePlugin());
	m_prefGeneral->pluginLineEdit->setText(gpppdata.pluginname());

	}
        if (gpppdata.protocol()=="pppoe")
	  m_prefGeneral->pppoeRadioButton->setChecked(TRUE);     
     }
         if (gpppdata.storedAccType()=="Dial up Modem") { 
         filterApply = "dialupEnabled";	 
         m_prefGeneral->widgetStack3->raiseWidget(2);	 
	if(gpppdata.modemDevice().isEmpty()){
	modemDev="/dev/modem";
	}
	else
	{
	modemDev=(gpppdata.modemDevice());
	}
	if(gpppdata.flowControl().isEmpty())
	flowControl="crtscts";
	else
	flowControl=(gpppdata.flowControl());
	
	if(gpppdata.speedControl().isEmpty())
	speedControl="57600";
	else
	speedControl=(gpppdata.speedControl());
	gpppdata.save();	 
	 
	 
	 
	 dialupAccounts();
     m_prefGeneral->dialupHeaderTextLabel->setText(i18n("<b><font color=\"#00aaff\" face=\"helvetica [Adobe]\"><h2>Making changes to	%1</h2></font></b>").arg(gpppdata.accname()) );     
     m_prefGeneral->accountlist_1->setEnabled(FALSE);
     m_prefGeneral->dialupNonRootCheckBox->setChecked(gpppdata.storeEnableRoot());
     m_prefGeneral->flowControlComboBox->setCurrentItem(gpppdata.flowControl());
     m_prefGeneral->dialupConnectionNameLineEdit->setText(gpppdata.accname());
     m_prefGeneral->dialupConnectionNameLineEdit->setEnabled(FALSE);
     m_prefGeneral->dialupUsernameLineEdit->setText(gpppdata.storedUsername());
     m_prefGeneral->dialupPasswordLineEdit->setText(gpppdata.storedPassword());
     m_prefGeneral->dialupPhoneLineEdit->setText(gpppdata.phoneNumber());
     m_prefGeneral->dialupAccountIconLineEdit->setText( gpppdata.accountIconName());
     m_prefGeneral->dialupTimeoutSpinBox->setValue( gpppdata.pppdTimeout() );
     m_prefGeneral->dialupIdleSpinBox->setValue( gpppdata.idleTimeout() );
     m_prefGeneral->dialupModemComboBox->setCurrentItem(gpppdata.modemDevice());   
     m_prefGeneral->defaultrouteCheckBox->setChecked(gpppdata.storeDefaultRoute());
     if (gpppdata.storedModemVolume()=="M0L0")
     m_prefGeneral->modemVolumeSlider->setValue(2);
     if (gpppdata.storedModemVolume()=="M1L1")     
      m_prefGeneral->modemVolumeSlider->setValue(1);    
     if (gpppdata.storedModemVolume()=="M1L3")           
      m_prefGeneral->modemVolumeSlider->setValue(0);        
     m_prefGeneral->dialupSpeedComboBox->setCurrentItem(gpppdata.speedControl());
     m_prefGeneral->lockCheckBox->setChecked(gpppdata.lockModem());    
	 
	 }
	}
	if(getuid()!=0)
	{
	m_prefGeneral->accountlist_1->setEnabled(FALSE);
	         filterApply = "nonRoot";
	 gpppdata.setAccount(item->text());
         m_prefGeneral->widgetStack3->raiseWidget(4);
	 m_prefGeneral->dialupAccountIconLineEdit_2->setText(gpppdata.accountIconName());
         if(gpppdata.storeUsage()==1) {
          m_prefGeneral->usageCheckBox_2->setChecked(gpppdata.storeUsage());
         m_prefGeneral->usageLineEdit_2->setText(gpppdata.usageURL());
         if (gpppdata.storeBrowserUsage()==1) {
	    m_prefGeneral->externalBrowserCheckBox_2->setChecked(gpppdata.storeBrowserUsage());
	    m_prefGeneral->browserLineEdit_2->setText(gpppdata.browserURL());
	 }
     }	 
	 
	}
}
     
     
void PrefDialog::slotListBoxSelect(QIconViewItem *item) {
   int idx = item->index()-1;
   if(idx!=-1) {
     QString account = gpppdata.accname();
     gpppdata.setAccountbyIndex(idx);
     gpppdata.setAccount(account);
     m_prefGeneral->connectionNameLineEdit->clear();
     m_prefGeneral->usernameLineEdit->clear();
     m_prefGeneral->passwordLineEdit->clear();
     m_prefGeneral->networkLineEdit->clear();
  m_prefGeneral->usernameLineEdit->setText(gpppdata.storedUsername());
 m_prefGeneral->passwordLineEdit->setText(gpppdata.storedPassword());
   }
   else {
     m_prefGeneral->connectionNameLineEdit->setEnabled(FALSE);
     m_prefGeneral->usernameLineEdit->setEnabled(FALSE);
     m_prefGeneral->passwordLineEdit->setEnabled(FALSE);
     m_prefGeneral->networkLineEdit->setEnabled(FALSE);
     m_prefGeneral->connectionNameLineEdit->clear();
     m_prefGeneral->usernameLineEdit->clear();
     m_prefGeneral->passwordLineEdit->clear();
     m_prefGeneral->networkLineEdit->clear();
     m_prefGeneral->usernameLineEdit->setText(gpppdata.storedUsername());
     m_prefGeneral->passwordLineEdit->setText(gpppdata.storedPassword());
   }
}

void PrefDialog::newDefaultTheme(int i) {
  gpppdata.setDefaultTheme(m_prefTheme->themeListBox->text(i));
  m_prefTheme->currentThemeTextLabel->setText(gpppdata.defaultTheme());
}


void PrefDialog::setStartTheme(){
     if (gpppdata.newtheme() == -1){
     gpppdata.setThemename(m_prefTheme->currentThemeTextLabel->text());
     gpppdata.save();
     m_prefTheme->currentThemeTextLabel->setText(gpppdata.themename()); }
     if(m_prefTheme->currentThemeTextLabel->text().isEmpty() ||
     !gpppdata.isUniqueThemename(m_prefTheme->themeLineEdit->text())) {
    return;
  } else {
    gpppdata.setThemename(m_prefTheme->currentThemeTextLabel->text());
  }
	QString themedir;
	themedir = gpppdata.themename();
	QString both = themedir + "/dock_left.png";
	dockicon = UserIcon (both);
	m_prefTheme->themeListBox->insertItem(dockicon, gpppdata.themename() );

 }

void PrefDialog::themeListBoxSelect(int idl) {
     if(idl!=-1) {
     QString themes = gpppdata.themename();
     gpppdata.setThemebyIndex(m_prefTheme->themeListBox->currentItem());
     gpppdata.setTheme(themes);
     }
}

void PrefDialog::deletetheme() {
     if(gpppdata.deleteTheme(m_prefTheme->themeListBox->text(m_prefTheme->themeListBox->currentItem())))
     m_prefTheme->themeListBox->removeItem(m_prefTheme->themeListBox->currentItem());
	themeListBoxSelect(m_prefTheme->themeListBox->currentItem());
}


void PrefDialog::newTheme() {

   KURL themeURL = KFileDialog::getOpenURL(0,"*.gz *.bz2|Gzip Files (*.gz) Bzip2 Files (*.bz2)", this,
                                              i18n("Drag or Type Theme URL"));

  if (themeURL.url().isEmpty()) return;

  QString themeTmpFile;
  #if KDE_IS_VERSION( 3, 1, 90 )
  if (!KIO::NetAccess::download(themeURL, themeTmpFile, this)) {
  #else
  if (!KIO::NetAccess::download(themeURL, themeTmpFile)) {
  #endif 
   QString sorryText;
    if (themeURL.isLocalFile())
       sorryText = i18n("Unable to find the icon theme archive %1!");
    else
       sorryText = i18n("Unable to download the icon theme archive!\n"
                        "Please check that address %1 is correct.");
    KMessageBox::sorry(this, sorryText.arg(themeURL.prettyURL()));
    return;
  }
 QStringList themesNames = findThemeDirs(themeTmpFile);
  if (themesNames.isEmpty()) {
    QString invalidArch(i18n("The file is not a valid icon theme archive!"));
    KMessageBox::error(this, invalidArch);

    KIO::NetAccess::removeTempFile(themeTmpFile);
    return;
  }
  if (!installThemes(themesNames, themeTmpFile)) {
    QString somethingWrong =
        i18n("A problem occurred during the installation process. "
             "However, most of the themes in the archive have been installed");
    KMessageBox::error(this, somethingWrong);
  }

  KIO::NetAccess::removeTempFile(themeTmpFile);
  
  KGlobal::instance()->newIconLoader();
  loadThemes();
}

QStringList PrefDialog::findThemeDirs(QString archiveName)
{
  QStringList foundThemes;

  KTar archive(archiveName);
  archive.open(IO_ReadOnly);
  const KArchiveDirectory* themeDir = archive.directory();

  KArchiveEntry* possibleDir = 0L;
  KArchiveDirectory* subDir = 0L;

  // iterate all the dirs looking for a kdsl icon
  QStringList entries = themeDir->entries();
  for (QStringList::Iterator it = entries.begin();
       it != entries.end();
       ++it) {
    possibleDir = const_cast<KArchiveEntry*>(themeDir->entry(*it));
    if (possibleDir->isDirectory()) {
      subDir = dynamic_cast<KArchiveDirectory*>( possibleDir );
      if (subDir->entry("dock_left.png") != NULL)
        foundThemes.append(subDir->name());
    }
  }

  archive.close();
  return foundThemes;
}

void PrefDialog::loadThemes() {
  QStringList themelist(KIconTheme::list());
  QString name;
  QString tname;
  QStringList::Iterator it;
  for (it=themelist.begin(); it != themelist.end(); it++)
  {
    KIconTheme icontheme(*it);
    if (icontheme.isHidden()) continue;

    name=icontheme.name();
    tname=name;

 //  Just in case we have duplicated icon theme names on separate directories
    for (int i=2; m_themeNames.find(tname)!=m_themeNames.end() ; i++)
        tname=QString("%1-%2").arg(name).arg(i);
  }

}

bool PrefDialog::installThemes(QStringList themes, QString archiveName)
{

    KStandardDirs *dirs = KGlobal::dirs();
    QString themePath;
    themePath = dirs->findResource ("data", "kdsl/pics/");
  bool everythingOk = true;
  QString localThemesDir(themePath);
  KTar archive(archiveName);
  archive.open(IO_ReadOnly);
  kapp->processEvents();

  const KArchiveDirectory* rootDir = archive.directory();

  KArchiveDirectory* currentTheme;
  for (QStringList::Iterator it = themes.begin();
       it != themes.end();
       ++it) {
    currentTheme = dynamic_cast<KArchiveDirectory*>(
                     const_cast<KArchiveEntry*>(
                       rootDir->entry(*it)));

   m_prefTheme->themeLineEdit->setText(*it);
   
     if (gpppdata.newtheme() == -1){
     gpppdata.setThemename(m_prefTheme->currentThemeTextLabel->text());
       }
    if (currentTheme == NULL) {
      // we tell back that something went wrong, but try to install as much
      // as possible
      everythingOk = false;
      continue;
    }
    currentTheme->copyTo(localThemesDir + *it);
  }
  archive.close();
  filterApply="themeInstall";
  return everythingOk;
}

void PrefDialog::dothemes() {
    m_prefTheme->currentThemeTextLabel->setText(gpppdata.themename());
}


void PrefDialog::dslAccounts()
{
    m_prefGeneral->ethernetComboBox->clear();
    m_prefGeneral->ethernetComboBox->insertItem("eth0");
    m_prefGeneral->ethernetComboBox->insertItem("eth1");
    m_prefGeneral->ethernetComboBox->insertItem("eth2");
    m_prefGeneral->ethernetComboBox->insertItem("eth3");
    m_prefGeneral->pluginLineEdit->setText(gpppdata.pluginname());
		    if(m_prefGeneral->usbCheckBox->isChecked()) {
		    
     		    m_prefGeneral->ethernetComboBox->insertItem("nas0");
     		    m_prefGeneral->ethernetComboBox->insertItem("tap0");	
		    }		  
}

void PrefDialog::dialupAccounts()
{
    m_prefGeneral->dialupModemComboBox->clear();
    m_prefGeneral->dialupModemComboBox->insertItem("/dev/modem");
    m_prefGeneral->dialupModemComboBox->insertItem("/dev/ttyS0");
    m_prefGeneral->dialupModemComboBox->insertItem("/dev/ttyS1");
    m_prefGeneral->dialupModemComboBox->insertItem("/dev/ttyS2");
    m_prefGeneral->dialupModemComboBox->insertItem("/dev/ttyS3");	   
    m_prefGeneral->dialupModemComboBox->insertItem("/dev/usb/ttyACM0");      
    m_prefGeneral->dialupModemComboBox->insertItem("/dev/usb/ttyACM1");       
    m_prefGeneral->dialupModemComboBox->insertItem("/dev/usb/ttyACM2");         
    m_prefGeneral->dialupModemComboBox->insertItem("/dev/usb/ttyACM3");             
}

void PrefDialog::enableApply()
{
    enableButtonApply(true);   // enable apply button  
}

void PrefDialog::slotCancel()
{
	  int i;
	  i=m_prefGeneral->widgetStack3->id(m_prefGeneral->widgetStack3->visibleWidget());
	if (activePageIndex()==0)
	  {
	  if(m_prefGeneral->widgetStack3->id(m_prefGeneral->widgetStack3->visibleWidget())==0 )
	  accept();
	   }
	   
        m_prefGeneral->widgetStack3->raiseWidget(0);
	showPage(0);
	filterApply ="none";
	m_prefGeneral->accountlist_1->clearSelection ();  	
	    if(getuid()!=0) {
	        m_prefGeneral->widgetStack3->raiseWidget(3);		
                m_prefGeneral->accountlist_1->setEnabled(TRUE);
	        m_prefGeneral->dslRadioButton->setChecked(FALSE);
	        m_prefGeneral->isdnRadioButton->setChecked(FALSE);       
	        m_prefGeneral->dialupRadioButton->setChecked(FALSE);     
            }
            else {
                m_prefGeneral->accountlist_1->setEnabled(TRUE);	
	    }

}
void PrefDialog::slotApply()
{
	m_prefAdvanced->applyTask();
    KStandardDirs *dirs = KGlobal::dirs();
    QString themePath;
    themePath = dirs->findResource ("data", "kdsl/pics/folder_red_open.png/");
if( filterApply !="none")    {
	if (filterApply == "dslNewEnabled"){
	if(m_prefGeneral->connectionNameLineEdit->text().isEmpty()) {
		KMessageBox::error(this,i18n("You must enter a name for this Broadband account"));
		return;
		}
         gpppdata.newaccount();

	 if(!gpppdata.isUniqueAccname(m_prefGeneral->connectionNameLineEdit->text()) ) {
	 KMessageBox::error(this, i18n("An Account already exits with this name.\nPlease choose another Account Name"));
	     return;
	     }
	 if(m_prefGeneral->checkBox4->isChecked()) {
	 if(m_prefGeneral->pluginLineEdit->text().isEmpty()) {
	 KMessageBox::error(this, i18n("You must select the plugin you wish to use if you enable plugins.\n To choose a plugin, click on the yellow folder in the section 'Path to Plugiins"));
	     return;
	     }	 
	     }
     gpppdata.setAccname(m_prefGeneral->connectionNameLineEdit->text());
      if (m_prefGeneral->accountIconLineEdit->text().isEmpty() ){
             KStandardDirs *dirs = KGlobal::dirs();
  	     QString themePath;
             themePath = dirs->findResource ("data", "kdsl/pics/folder_red_open.png");     
           gpppdata.setAccountIconName(themePath);	     
	   }
      else{
      gpppdata.setAccountIconName(m_prefGeneral->accountIconLineEdit->text());
      }
      (void) new QIconViewItem( m_prefGeneral->accountlist_1, ( gpppdata.accname()), gpppdata.accountIconName()  );    
     gpppdata.setStoredUsername(m_prefGeneral->usernameLineEdit->text());
     gpppdata.setStoredPassword(m_prefGeneral->passwordLineEdit->text());
     gpppdata.setPluginName(m_prefGeneral->pluginLineEdit->text());
     if (m_prefGeneral->pppoeRadioButton->isChecked() )
	 gpppdata.setProtocol("pppoe");
     if (m_prefGeneral->pppoaRadioButton->isChecked() )
	 gpppdata.setProtocol("pppoa");
     gpppdata.setStoreConnect(m_prefAdvanced->startupCheckBox->isChecked());	
     gpppdata.setStoreClock(m_prefAdvanced->timeCheckBox->isChecked());     
     gpppdata.setStoreEnableSound(m_prefAdvanced->soundCheckBox->isChecked());
     gpppdata.set_usb(m_prefGeneral->usbCheckBox->isChecked());    
     if (m_prefGeneral->usageCheckBox->isChecked()) {
         gpppdata.setStoreUsage(TRUE);
         gpppdata.setUsageURL(m_prefGeneral->usageLineEdit->text());
     }
     else
     {
          gpppdata.setStoreUsage(FALSE);
	  }    
	if(m_prefGeneral->externalBrowserCheckBox->isChecked()) {
	gpppdata.setStoreBrowserUsage(TRUE);
	gpppdata.setBrowserURL(m_prefGeneral->browserLineEdit->text());
	}
	else
	{
	gpppdata.setStoreBrowserUsage(FALSE);	
	m_prefGeneral->browserLineEdit->clear();
	gpppdata.setBrowserURL(m_prefGeneral->browserLineEdit->text());
	}
 	if (m_prefGeneral->dslRadioButton->isChecked() )
	gpppdata.setStoredAccType(m_prefGeneral->dslRadioButton->text());
	if (m_prefGeneral->isdnRadioButton->isChecked() )
	gpppdata.setStoredAccType(m_prefGeneral->isdnRadioButton->text());	
	if (m_prefGeneral->dialupRadioButton->isChecked() )
	gpppdata.setStoredAccType(m_prefGeneral->dialupRadioButton->text());		
	gpppdata.setStoreHideIP(m_prefAdvanced->showIPCheckBox->isChecked());	
        gpppdata.setStoreAutostart(m_prefAdvanced->kdeStartupCheckBox->isChecked());	
	gpppdata.setStoreUsePlugin(m_prefGeneral->checkBox4->isChecked());	 
	gpppdata.setStoreEnableNotify(m_prefAdvanced->disableNotifyCheckBox->isChecked());	
	gpppdata.setpppdTimeout(m_prefGeneral->kIntNumInput1->value()) ;    
	emit resetaccounts();
	WriteOptions();
	WritePapsecrets();		
		
		
	}
	if (filterApply == "dialupNewEnabled"){	
	if(m_prefGeneral->dialupConnectionNameLineEdit->text().isEmpty()) {
		KMessageBox::error(this,i18n("You must enter a name for this dialup account"));
		return;
		}
         gpppdata.newaccount();

     gpppdata.setAccname(m_prefGeneral->dialupConnectionNameLineEdit->text());
      if (m_prefGeneral->dialupAccountIconLineEdit->text().isEmpty() )
           gpppdata.setAccountIconName(themePath);
      else
      gpppdata.setAccountIconName(m_prefGeneral->dialupAccountIconLineEdit->text());
      (void) new QIconViewItem( m_prefGeneral->accountlist_1, ( gpppdata.accname()), gpppdata.accountIconName()  );    
     gpppdata.setStoredUsername(m_prefGeneral->dialupUsernameLineEdit->text());
     gpppdata.setStoredPassword(m_prefGeneral->dialupPasswordLineEdit->text());
     gpppdata.setStoredAccType(m_prefGeneral->dialupRadioButton->text());     
     gpppdata.setPhoneNumber(m_prefGeneral->dialupPhoneLineEdit->text());
     gpppdata.setStoreDefaultRoute(m_prefGeneral->defaultrouteCheckBox->isChecked());		
	emit resetaccounts();
	WriteOptions();
	WritePapsecrets();				
	}

      if (filterApply == "dslEnabled") {

            applyDslSettings();
        m_prefGeneral->accountlist_1->currentItem()->setPixmap(m_prefGeneral->accountIconLineEdit->text());	  
	}    

      if (filterApply == "dialupEnabled"){
            applyDialupSettings();
        m_prefGeneral->accountlist_1->currentItem()->setPixmap(m_prefGeneral->dialupAccountIconLineEdit->text());	  
	}  

	if (filterApply == "nonRoot") {
            if (m_prefGeneral->dialupAccountIconLineEdit_2->text().isEmpty() ){
                KStandardDirs *dirs = KGlobal::dirs();
  	        QString themePath;
                themePath = dirs->findResource ("data", "kdsl/pics/folder_red_open.png");     
                gpppdata.setAccountIconName(themePath);	     
	      }
	      else
	gpppdata.setAccountIconName(m_prefGeneral->dialupAccountIconLineEdit_2->text());	      
	      	
	 
	     if (m_prefGeneral->usageCheckBox_2->isChecked()) {
         gpppdata.setStoreUsage(TRUE);
         gpppdata.setUsageURL(m_prefGeneral->usageLineEdit_2->text());
         }
         else
         {
          gpppdata.setStoreUsage(FALSE);
	  }    
	if(m_prefGeneral->externalBrowserCheckBox_2->isChecked()) {
	gpppdata.setStoreBrowserUsage(TRUE);
	gpppdata.setBrowserURL(m_prefGeneral->browserLineEdit_2->text());
	}
	else
	{
	gpppdata.setStoreBrowserUsage(FALSE);	
	m_prefGeneral->browserLineEdit_2->clear();
	gpppdata.setBrowserURL(m_prefGeneral->browserLineEdit_2->text());
	}
	m_prefGeneral->accountlist_1->currentItem()->setPixmap(m_prefGeneral->dialupAccountIconLineEdit_2->text());	 
	m_prefGeneral->accountlist_1->clearSelection (); 	
	emit resetaccounts();	
	m_prefGeneral->accountlist_1->clearSelection ();  	
	}	 		
}
	 
	m_prefGeneral->accountlist_1->clearSelection ();  

gpppdata.setStoreEnableSound(m_prefAdvanced->soundCheckBox->isChecked());
gpppdata.setStoreEnableNotify(m_prefAdvanced->disableNotifyCheckBox->isChecked());
gpppdata.setStoreHideIP(m_prefAdvanced->showIPCheckBox->isChecked());
gpppdata.setStoreAutostart(m_prefAdvanced->kdeStartupCheckBox->isChecked());
gpppdata.setStoreClock(m_prefAdvanced->timeCheckBox->isChecked());
gpppdata.setStoreConnect(m_prefAdvanced->startupCheckBox->isChecked());
gpppdata.setLockModem(m_prefGeneral->lockCheckBox->isChecked());
emit resetaccounts();
    if(gpppdata.themename().isEmpty()) {
        gpppdata.setThemename(m_prefTheme->themeLineEdit->text());
	QString themedir;
	themedir = gpppdata.themename();
	QString both = themedir + "/dock_left.png";
	dockicon = UserIcon (both);
	m_prefTheme->themeListBox->insertItem(dockicon, gpppdata.themename() );
    }
	m_prefTheme->themeLineEdit->clear();
	m_prefTheme->themeLineEdit->setEnabled(FALSE);
        m_prefGeneral->widgetStack3->raiseWidget(0);
        if(getuid()!=0) {
		m_prefGeneral->widgetStack3->raiseWidget(3);
		m_prefGeneral->dslRadioButton->setChecked(false);
		m_prefGeneral->isdnRadioButton->setChecked(false);
		m_prefGeneral->dialupRadioButton->setChecked(false);
		m_prefGeneral->accountlist_1->setEnabled(TRUE);
	filterApply ="none";	
	m_prefGeneral->accountlist_1->clearSelection ();  	
	}
	else 
		m_prefGeneral->accountlist_1->setEnabled(TRUE);
	filterApply ="none";
	m_prefGeneral->accountlist_1->clearSelection ();  	


}
void PrefDialog::slotDefault()
{
}

void PrefDialog::allowAccount(const QString &n)
{

	if(!gpppdata.storeEnableRoot()) {
	QString deletePath="/etc/ppp/kdsl/delete.Accounts";
	QString accountdelete;
	accountdelete=n;
	QFile file(deletePath);
        QTextStream stream( &file );		
	if ( file.open( (IO_WriteOnly | IO_Append) ) ) {
	stream << accountdelete;
	stream << "\n";
	}
	file.close();	
	}
	if(gpppdata.storeEnableRoot())
	{
	    QString accountPath="/etc/ppp/kdsl/delete.Accounts";
	    QString accountdelete, textstring, newstring;
	    accountdelete=n;	
	    QRegExp expression;
	    expression.setPattern(accountdelete);	
	    QFile file(accountPath);	
	    QTextStream instream , outstream;
	    if ((file.open(IO_ReadOnly)) == 0) {
	    }
	    outstream.setDevice(&file);
  	    textstring = outstream.read();
	    file.close();
	if (textstring.find(expression, 0) ==-1)
	{
        	textstring.remove(accountdelete);
		newstring = "";
		textstring.insert(0, newstring);
	}
	else
	{
		newstring ="";
		textstring.remove(accountdelete);
		textstring.replace(expression, newstring);
	}
	if ((file.open(IO_WriteOnly)) == 0)
	return;
	instream.setDevice(&file);
	instream << textstring;
	file.close();
	} 
}
void PrefDialog::applyDslSettings()
{

	gpppdata.setAccname(m_prefGeneral->connectionNameLineEdit->text());
        gpppdata.setStorePassword(m_prefGeneral->store_password->isChecked());
        gpppdata.setStoredUsername(m_prefGeneral->usernameLineEdit->text());
	gpppdata.setStoreEnableRoot(m_prefGeneral->nonRootCheckBox->isChecked());	
	if(getuid()==0) {
	allowAccount(m_prefGeneral->connectionNameLineEdit->text());

}
        gpppdata.setStoredPassword(m_prefGeneral->passwordLineEdit->text());
        gpppdata.setPluginName(m_prefGeneral->pluginLineEdit->text());
	gpppdata.setStoreUsePlugin(m_prefGeneral->checkBox4->isChecked());	 
	gpppdata.setStoredAccType(m_prefGeneral->dslRadioButton->text());
	gpppdata.setpppdTimeout(m_prefGeneral->kIntNumInput1->value()) ;  
	 gpppdata.setStoredEthDevice(ethDevice);	
	 if(m_prefGeneral->checkBox4->isChecked()) {
	 if(m_prefGeneral->pluginLineEdit->text().isEmpty()) {
	 KMessageBox::error(this, i18n("You must select the plugin you wish to use if you enable plugins.\n To choose a plugin, click on the yellow folder in the section 'Path to Plugiins"));
	     return;
	     }	 
	     }	
	   if (m_prefGeneral->pppoeRadioButton->isChecked() )
	     gpppdata.setProtocol("pppoe");
	   if (m_prefGeneral->pppoaRadioButton->isChecked() )
	     gpppdata.setProtocol("pppoa");
	   if(m_prefGeneral->dnsRadioButton->isChecked() ) 
	     gpppdata.setAutoDNS(TRUE);	
	     else
	     gpppdata.setAutoDNS(FALSE);
	   if(!m_prefGeneral->accountIconLineEdit->text().isEmpty()) {
	     gpppdata.setAccountIconName(m_prefGeneral->accountIconLineEdit->text() );
	     }
	   else
	     {
    KStandardDirs *dirs = KGlobal::dirs();
    QString iconPath;
    iconPath = dirs->findResource ("data", "kdsl/pics/");
	     }
	m_prefGeneral->accountlist_1->repaintSelectedItems();
        gpppdata.setThemename(m_prefTheme->themeLineEdit->text());
	QString themedir;
	themedir = gpppdata.themename();
	QString both = themedir + "/dock_left.png";
	dockicon = UserIcon (both);
	m_prefTheme->themeListBox->insertItem(dockicon, gpppdata.themename() );	
	     if (m_prefGeneral->usageCheckBox->isChecked()) {
         gpppdata.setStoreUsage(TRUE);
         gpppdata.setUsageURL(m_prefGeneral->usageLineEdit->text());
     }
     else
     {
          gpppdata.setStoreUsage(FALSE);
	  }    
	if(m_prefGeneral->externalBrowserCheckBox->isChecked()) {
	gpppdata.setStoreBrowserUsage(TRUE);
	gpppdata.setBrowserURL(m_prefGeneral->browserLineEdit->text());
	}
	else
	{
	gpppdata.setStoreBrowserUsage(FALSE);	
	m_prefGeneral->browserLineEdit->clear();
	gpppdata.setBrowserURL(m_prefGeneral->browserLineEdit->text());
	}
	WriteOptions();	
	emit resetaccounts();  
//	WriteOptions();
	WritePapsecrets();	     
}

void PrefDialog::applyDialupSettings()     
{	
	
	gpppdata.setModemDevice(modemDev);
	gpppdata.setFlowControl(flowControl);
	gpppdata.setSpeedControl(speedControl);			
	gpppdata.setStoredAccType(m_prefGeneral->dialupRadioButton->text());
	gpppdata.setAccname(m_prefGeneral->dialupConnectionNameLineEdit->text());
	gpppdata.setPhoneNumber(m_prefGeneral->dialupPhoneLineEdit->text());
	gpppdata.setStoreEnableRoot(m_prefGeneral->dialupNonRootCheckBox->isChecked());
	if(getuid()==0) {
	allowAccount(m_prefGeneral->dialupConnectionNameLineEdit->text());
	}
        gpppdata.setStoredUsername(m_prefGeneral->dialupUsernameLineEdit->text());
        gpppdata.setStoredPassword(m_prefGeneral->dialupPasswordLineEdit->text());
	gpppdata.setpppdTimeout(m_prefGeneral->dialupTimeoutSpinBox->value()) ;  
	gpppdata.setIIdleTimeout(m_prefGeneral->dialupIdleSpinBox->value()) ;  
	gpppdata.setStoreDefaultRoute(m_prefGeneral->defaultrouteCheckBox->isChecked());	 
	   if(m_prefGeneral->dialupAccountIconLineEdit->text() !="") {
	     gpppdata.setAccountIconName(m_prefGeneral->dialupAccountIconLineEdit->text() );
	     }
	   else
	     {
    KStandardDirs *dirs = KGlobal::dirs();
    QString iconPath;
    iconPath = dirs->findResource ("data", "kdsl/pics/");
	     }

        gpppdata.setThemename(m_prefTheme->themeLineEdit->text());
	QString themedir;
	themedir = gpppdata.themename();
	QString both = themedir + "/dock_left.png";
	dockicon = UserIcon (both);
	m_prefTheme->themeListBox->insertItem(dockicon, gpppdata.themename() );	
	WriteOptions();	
	emit resetaccounts();  
	WritePapsecrets();	     
}

void PrefDialog::applyIsdnSettings()
{

}

 int PrefDialog::WritePapsecrets() {
	// Firstly we check to see if /etc/ppp/kdsl/ exists.  If not, we create the directory.
	 
	QFile papsecrets, options, chapsecrets;
	QString searchstring, papfilestring, chapfilestring, textstring, newstring, password;
	QRegExp expression;
	QTextStream outstream, instream;
	password = m_prefGeneral->passwordLineEdit->text();

	searchstring = '"' + m_prefGeneral->usernameLineEdit->text() + '"' + "[\\s\t]+[^\".]+[\\s\t]+\"[^\".]+\"";
	password ='"' + m_prefGeneral->usernameLineEdit->text() + '"' + " * " + '"' + '"'+ '\n';
	expression.setPattern(searchstring);
	papfilestring = "/etc/ppp/pap-secrets";
	chapfilestring = "/etc/ppp/chap-secrets";

	papsecrets.setName(papfilestring);
	papsecrets.encodeName(papfilestring);
	chapsecrets.setName(chapfilestring);
	if ((papsecrets.open(IO_ReadOnly)) == 0) {

	}

	outstream.setDevice(&papsecrets);
  	textstring = outstream.read();
	papsecrets.close();



	if (textstring.find(expression, 0) ==-1)
	{

	textstring.remove(password);
		newstring = '"' + m_prefGeneral->usernameLineEdit->text() + '"' + " * " + '"' + m_prefGeneral->passwordLineEdit->text() + '"' + '\n';
		textstring.insert(0, newstring);
	}
	else
	{
		newstring = '"' + m_prefGeneral->usernameLineEdit->text() + '"' + " * " + '"' +  m_prefGeneral->passwordLineEdit->text() + '"';
		textstring.remove(password);
		textstring.replace(expression, newstring);
	}


	if ((papsecrets.open(IO_WriteOnly)) == 0) return ERROR_OPENING_PAPSECRETS_FOR_WRITE;
	instream.setDevice(&papsecrets);
	instream << textstring;
	papsecrets.close();

	if ((chapsecrets.open(IO_WriteOnly)) == 0) return ERROR_OPENING_CHAPSECRETS_FOR_WRITE;
	instream.setDevice(&chapsecrets);
	instream << textstring;
	chapsecrets.close();
	return EVERYTHING_OK;
 }

 int PrefDialog::WriteOptions() {
/**
  Here we write the config file to /etc/ppp/kdsl/options.*username*.  Pppd will iterate through the file to make the connection.

  */
	if(getuid() !=0) {
	return 1;
	}
	QFile Poptions;
	QString Pfilestring;
	QString Paccountname;
	QTextStream outstream, instream;
	if(gpppdata.storedAccType()=="DSL") {
	Pfilestring = PPPOEPATH + m_prefGeneral->connectionNameLineEdit->text();	
	Paccountname = m_prefGeneral->connectionNameLineEdit->text();
	}
        if(gpppdata.storedAccType()=="Dial up Modem") {
	Pfilestring = PPPOEPATH + m_prefGeneral->dialupConnectionNameLineEdit->text();		
	Paccountname = m_prefGeneral->dialupConnectionNameLineEdit->text();
	}
	Poptions.setName(Pfilestring);

	if ((Poptions.open(IO_WriteOnly)) == 0) KMessageBox::error(this, i18n("Can't open"));
	instream.setDevice(&Poptions);
	if(gpppdata.storedAccType()=="DSL") {		
	if(gpppdata.storeUsePlugin()==1) {
	instream << "plugin " << m_prefGeneral->pluginLineEdit->text(); instream << "\n";
	instream << ethDevice; instream << "\n";	
	}
	else {
	if (gpppdata.protocol()=="pppoe") {
	instream << "pty ";  instream << "'/usr/sbin/pppoe -I "; instream << ethDevice ;  instream << "'\n";
        }
	  if (gpppdata.protocol()=="pppoa") {
	    instream << "pty "; instream << " '/usr/sbin/pppoa3 -c -vpi 8 -vci 35'\n";
	    instream << "holdoff 4\nmaxfail 25\n";
	  }
	}
	instream << "defaultroute\n";
}
	if(gpppdata.storedAccType()=="Dial up Modem") {
	instream << modemDev ;  instream << "\n";
	instream << gpppdata.speedControl(); instream <<"\n";   //"57600\n";
	instream << "asyncmap 0\n";
	instream << gpppdata.flowControl(); instream <<"\n"; //"crtscts\n";
	instream << "modem\n";
	if (m_prefGeneral->lockCheckBox->isChecked())
	    instream << "lock\n";
	}
	instream << "logfile " << log_file; instream << "\n";
        if (m_prefGeneral->dnsRadioButton->isChecked()) {
	instream << "usepeerdns\n"; }
	if (gpppdata.storeDefaultRoute())
	instream << "defaultroute\n";
	instream << "hide-password\n";
 	if(gpppdata.storedAccType()=="DSL") {	       
	instream << "mru 1492\n";
	instream << "mtu 1492\n";
	}
	else
	{
	instream << "mru 552\n";
	instream << "mtu 552\n";
}	
	instream << "lcp-echo-interval 10\n";
	instream << "lcp-echo-failure 3\n";
	instream << "nodetach\n";
	instream << "idle " << gpppdata.idleTimeout()*60; instream << "\n";
	if(gpppdata.storedAccType()=="DSL")
	instream << "user " << m_prefGeneral->usernameLineEdit->text(); instream << "\n";
	if(gpppdata.storedAccType()=="Dial up Modem")	{
	instream << "user " << m_prefGeneral->dialupUsernameLineEdit->text(); instream << "\n";	
	QString dialupstuff = "'\\d\\c'";
	instream << "connect ";  instream << '"'; instream << "/usr/sbin/chat -v '' atz OK AT"; instream << gpppdata.storedModemVolume(); instream << " OK ATDT" <<m_prefGeneral->dialupPhoneLineEdit->text(); instream << " CONNECT "; instream <<  dialupstuff; instream <<  '"';  instream << "\n"; 
	}
	Poptions.close();
	QFile accounts;
	QString accountNames;
	if(gpppdata.storedAccType()=="DSL")
	accountNames="/etc/ppp/kdsl/Accounts/"+ m_prefGeneral->connectionNameLineEdit->text();		
	if(gpppdata.storedAccType()=="Dial up Modem")		
	accountNames="/etc/ppp/kdsl/Accounts/"+ m_prefGeneral->dialupConnectionNameLineEdit->text();	
	accounts.setName(accountNames);
	if ((accounts.open(IO_WriteOnly)) == 0) KMessageBox::error(this, i18n("Can't open"));	
	instream.setDevice(&accounts);	
	instream << gpppdata.accountIconName();  instream << "\n";	
	accounts.close();	
	return EVERYTHING_OK;  
} 

void PrefDialog::comboBoxItemActivated( int eth) {

 	if(gpppdata.storedAccType()=="DSL") {
	switch ( eth ) {
    	default:
    		case 0:
		ethDevice="eth0";
		break;
   		case 1:
		ethDevice="eth1";
		break;
   	 	case 2:
		ethDevice="eth2";
		break;
  	  	case 3:
		ethDevice="eth3";
		break;
			  if(gpppdata.get_usb()) {
	                        case 4:
				ethDevice="nas0";
				break;
				case 5:
				ethDevice="tap0";
				break;
	     		   }	
               }
	        gpppdata.setStoredEthDevice(ethDevice);
		gpppdata.save();
	  }
}

void PrefDialog::dialupComboBoxItemActivated( int eth) {
	  if(gpppdata.storedAccType()=="ISDN") {
	  }

	if(gpppdata.storedAccType()== "Dial up Modem") { 
	switch ( eth ) {	
   	default:
    		case 0:
		modemDev="/dev/modem";
		break;
   		case 1:
		modemDev="/dev/ttyS0";
		break;
   	 	case 2:
		modemDev="/dev/ttyS1";
		break;
  	  	case 3:
		modemDev="/dev/ttyS2";
		break;	
		case 4:
		modemDev="/dev/ttyS3";
		break;
		case 5:
		modemDev="/dev/usb/ttyACM0";
		break;
		case 6:
		modemDev="/dev/usb/ttyACM1";
		break;	
		case 7:
		modemDev="/dev/usb/ttyACM2";
		break;
		case 8:
		modemDev="/dev/usb/ttyACM3";
		break;						
		}
		modemDev=m_prefGeneral->dialupModemComboBox->text(eth);
		gpppdata.setModemDevice(modemDev);
		gpppdata.save();		
	}

}
void PrefDialog::flowComboBoxItemActivated( int eth) {

	if(gpppdata.storedAccType()== "Dial up Modem") { 
	switch ( eth ) {	
   	default:
    		case 0:
		flowControl="crtscts";
		break;
   		case 1:
		flowControl="xonxoff";
		break;
   	 	case 2:
		flowControl="";
		break;
		}
		gpppdata.setFlowControl(flowControl);	
		gpppdata.save();
	}
}

void PrefDialog::modemVolumeActivated(int vol) {
		switch ( vol) {
		default:
			case 0:
			modemVolume="M1L3";
			break;
			case 1:
			modemVolume="M1L1";
			break;
			case 2:
			modemVolume="M0L0";		
			break;
			}
		gpppdata.setStoredModemVolume(modemVolume);
		gpppdata.save();
}
			
void PrefDialog::modemSpeedComboBoxItemActivated( int eth) {

	if(gpppdata.storedAccType()== "Dial up Modem") { 
	switch ( eth ) {	
   	default:
    		case 0:
		speedControl="460800";
		break;
   		case 1:
		speedControl="230400";
		break;
   	 	case 2:
		speedControl="115200";
		break;
   	 	case 3:
		speedControl="57600";
		break;	
   	 	case 4:
		speedControl="38400";
		break;	
   	 	case 5:
		speedControl="19200";
		break;	
   	 	case 6:
		speedControl="9600";
		break;
   	 	case 7:
		speedControl="2400";
		break;										
		}
		gpppdata.setSpeedControl(speedControl);
		gpppdata.save();
	}
}
