// (c) 2000 Peter Putzer <putzer@kde.org>

#include <tqtimer.h>
#include <tqfileinfo.h>
#include <tqlayout.h>
#include <tqtooltip.h>

#include <kdebug.h>
#include <kiconloader.h>
#include <kdialog.h>
#include <tdelocale.h>

#include "ksv_core.h"
#include "RunlevelAuthIcon.h"
#include <tqlabel.h>

RunlevelAuthIcon::RunlevelAuthIcon (const TQString& servicesPath, const TQString& runlevelPath,
									TQWidget* parent, const char* name)
  : KAuthIcon (parent, name),
	mTimer (new TQTimer (this)),
	mServicesInfo (new TQFileInfo (servicesPath)),
    mRLInfo (new TQFileInfo* [ksv::runlevelNumber]),
	mOld (false),
	mInterval (1000),
    mCheckEnabled(false)
{
  lockText = i18n("Editing disabled - please check your permissions");
  openLockText = i18n("Editing enabled");

  lockLabel->setText (lockText);
  lockLabel->hide();

  lockPM = UserIcon ("ksysv_locked");
  openLockPM = UserIcon ("ksysv_unlocked");

  lockBox->setPixmap (lockPM);

  lockBox->setMargin (1);
  lockBox->setFrameStyle (TQFrame::NoFrame);
  lockBox->setFixedSize (lockBox->sizeHint());

  connect (mTimer, TQ_SIGNAL (timeout()), this, TQ_SLOT (timerEvent()));
  mTimer->start (mInterval);

  for (int i = 0; i < ksv::runlevelNumber; ++i)
	{
	  mRLInfo[i] = new TQFileInfo ((runlevelPath + "/rc%1.d").arg(i));
	}

  updateStatus();
  layout->activate();
}

RunlevelAuthIcon::~RunlevelAuthIcon ()
{
  delete mServicesInfo;

  for (int i = 0; i < ksv::runlevelNumber; ++i)
	{
	  delete mRLInfo[i];
	}

  delete[] mRLInfo;
}

void RunlevelAuthIcon::updateStatus ()
{
  if (!mCheckEnabled)
    return;

  const bool res = status();

  if (mOld != res)
	{
	  lockBox->setPixmap (res ? openLockPM : lockPM);
	  lockLabel->setText (res ? openLockText : lockText);

	  TQToolTip::remove (this);
	  TQToolTip::add (this, lockLabel->text());

      mOld = res;
	  emit authChanged (res);
	}
  else
    mOld = res;
}

bool RunlevelAuthIcon::status () const
{
  bool result = mServicesInfo->isWritable();

  for (int i = 0; i < ksv::runlevelNumber; ++i)
    result = result && mRLInfo[i]->isWritable();

  return result;
}

void RunlevelAuthIcon::timerEvent ()
{
  for (int i = 0; i < ksv::runlevelNumber; ++i)
	{
	  mRLInfo[i]->refresh();
	}
  
  mServicesInfo->refresh();

  updateStatus();
}

void RunlevelAuthIcon::setServicesPath (const TQString& path)
{
  mTimer->stop();

  mServicesInfo->setFile (path);

  mTimer->start(mInterval);
}

void RunlevelAuthIcon::setRunlevelPath (const TQString& path)
{
  mTimer->stop();

  for (int i = 0; i < ksv::runlevelNumber; ++i)
	{
	  mRLInfo[i]->setFile ((path + "/rc%1.d").arg(i));
	}

  mTimer->start(mInterval);
}

void RunlevelAuthIcon::setRefreshInterval (int interval)
{
  mInterval = interval;

  mTimer->stop();
  mTimer->start (mInterval);
}

void RunlevelAuthIcon::setCheckEnabled (bool on)
{
  kdDebug(3000) << "enabling authicon " << on << endl;
  mCheckEnabled = on;

  // refresh everything
  mOld = !status();
  timerEvent();
}

#include "RunlevelAuthIcon.moc"
