/*
This file is part of the KDE project
Copyright (C) 2004 Martijn Klingens <klingens@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; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/

#include <tqlayout.h>
#include <tqwhatsthis.h>
#include <tqvgroupbox.h>
#include <tqpushbutton.h>
#include <tqheader.h>
#include <tqtimer.h>
#include <tqfileinfo.h>

#include <tdeaboutdata.h>
#include <tdeapplication.h>
#include <tdedesktopfile.h>
#include <kdialog.h>
#include <kgenericfactory.h>
#include <tdelistview.h>
#include <tdemessagebox.h>
#include <kservice.h>
#include <tdestandarddirs.h>

#include <dcopclient.h>
#include <dcopref.h>

#include <kdebug.h>

#include "kcmautostart.h"
#include "kcmautostart.moc"

typedef KGenericFactory<AutoStartConfig, TQWidget> AutoStartFactory;
K_EXPORT_COMPONENT_FACTORY( kcm_autostart, AutoStartFactory( "kcmautostart" ) )

AutoStartConfig::AutoStartConfig(TQWidget* parent, const char* name, const TQStringList &) :
    TDECModule( AutoStartFactory::instance(), parent, name )
{
    TDEGlobal::dirs()->addResourceType("autostart", "share/autostart");
    TDEAboutData *about =
        new TDEAboutData( I18N_NOOP( "kcmautostart" ), I18N_NOOP( "TDE Service Manager" ),
            0, 0, TDEAboutData::License_GPL, I18N_NOOP( "(c) 2004 Martijn Klingens" ) );
    about->addAuthor( "Martijn Klingens", 0, "klingens@kde.org" );
    setAboutData( about );

    TQVBoxLayout *lay = new TQVBoxLayout( this, 0, KDialog::spacingHint() );

    TQGroupBox *gb = new TQVGroupBox( i18n( "Startup Services" ), this );
    TQWhatsThis::add(gb, i18n("This shows all TDE services that can be loaded "
                "on TDE startup. Checked services will be invoked on next startup. "
                "Be careful with deactivation of unknown services."));
    lay->addWidget( gb );

    _lvStartup = new TDEListView( gb );
    _lvStartup->addColumn(i18n("Use"));
    _lvStartup->addColumn(i18n("Service"));
    _lvStartup->addColumn(i18n("Description"));
    _lvStartup->setAllColumnsShowFocus(true);
    _lvStartup->header()->setStretchEnabled(true, 2);

    load();
}

void setModuleGroup(TDEConfig *config, const TQString &filename)
{
    TQString module = filename;
    int i = module.findRev('/');
    if (i != -1)
    module = module.mid(i+1);
    i = module.findRev('.');
    if (i != -1)
    module = module.left(i);

    config->setGroup(TQString("Module-%1").arg(module));
}

bool AutoStartConfig::autoloadEnabled(TDEConfig *config, const TQString &filename)
{
    setModuleGroup(config, filename);
    return config->readBoolEntry("autoload", true);
}

void AutoStartConfig::setAutoloadEnabled(TDEConfig *config, const TQString &filename, bool b)
{
    setModuleGroup(config, filename);
    return config->writeEntry("autoload", b);
}

void AutoStartConfig::load() {
    _lvStartup->clear();

    TQStringList files = TDEGlobal::dirs()->findAllResources( "autostart", TQString::fromLatin1( "*.desktop" ), false, true );

    for ( TQStringList::ConstIterator it = files.begin(); it != files.end(); it++ )
    {
        if ( TDEDesktopFile::isDesktopFile( TQFileInfo( *it ).fileName() ) )
        {
            TDEDesktopFile file( TQFileInfo( *it ).fileName(), true, "autostart" );
            TQString name = file.readName();
            if ( !name.isEmpty() )
            {
                CheckListItem *clitem = new CheckListItem( _lvStartup, TQString() );
                connect( clitem, TQ_SIGNAL( changed( TQCheckListItem * ) ), TQ_SLOT( slotItemChecked( TQCheckListItem * ) ) );
                clitem->setText( 1, name );
                clitem->setText( 2, file.readComment() );
                clitem->setText( 3, *it );
                clitem->setOn( !file.readBoolEntry( "Hidden", false ) );
            }
        }
    }
}

void AutoStartConfig::save()
{
    TQListViewItemIterator it( _lvStartup );
    while ( it.current() )
    {
        if ( TDEDesktopFile::isDesktopFile( it.current()->text( 3 ) ) )
        {
            // Determine whether we need to change the file on a readonly desktop file
            // by giving a full path first
            TQString path = it.current()->text( 3 );
            TDEDesktopFile file( path, true, "services" );
            bool shouldBeHidden = !( static_cast<TQCheckListItem *>( it.current() )->isOn() );
            if ( file.readBoolEntry( "Hidden", false ) != shouldBeHidden )
            {
                TDEDesktopFile outFile( TQFileInfo( path ).fileName(), false, "autostart" );
                kdDebug() << "************** Writing out " << path << endl;
                outFile.writeEntry( "Hidden", shouldBeHidden );
                outFile.sync();
            }
        }
        ++it;
    }

    //TQTimer::singleShot(0, this, TQ_SLOT(slotServiceRunningToggled()));
}

void AutoStartConfig::defaults()
{
    TQListViewItemIterator it( _lvStartup);
    while ( it.current() != 0 ) {
        if (it.current()->rtti()==1) {
            TQCheckListItem *item = static_cast<TQCheckListItem *>(it.current());
            item->setOn(false);
        }
        ++it;
    }
}

void AutoStartConfig::slotReload()
{
    TQString current = _lvStartup->currentItem()->text(4);
    load();
    TQListViewItem *item = _lvStartup->findItem(current, 4);
    if (item)
        _lvStartup->setCurrentItem(item);
}

void AutoStartConfig::slotItemChecked(TQCheckListItem*)
{
    emit changed(true);
}

TQString AutoStartConfig::quickHelp() const
{
    return i18n("<h1>Service Manager</h1><p>This module allows you to have an overview of all plugins "
            "running as TDE Services. Generally, there are two types of service:</p>"
            "<ul><li>Services invoked at startup</li><li>Services called on demand</li></ul>"
            "<p>The latter are only listed for convenience. The startup services can be started and stopped. "
            "In Administrator mode, you can also define whether services should be loaded at startup.</p>"
            "<p><b> Use this with care: some services are vital for TDE; do not deactivate services if you"
            " do not know what you are doing.</b></p>");
}

CheckListItem::CheckListItem(TQListView *parent, const TQString &text)
    : TQObject(parent),
    TQCheckListItem(parent, text, CheckBox)
{ }

void CheckListItem::stateChange(bool on)
{
    TQCheckListItem::stateChange(on);
    emit changed(this);
}
