/*
* qmail.cpp -- Implementation of class KQMailDrop.
* Author:	Sirtaj Singh Kang
* Version:	$Id: qmail.cpp,v 1.3 1999/09/22 17:54:54 dfaure Exp $
* Generated:	Mon Dec  1 00:45:12 EST 1997
*/

#include<assert.h>



#include<qdatetm.h>
#include<qfileinf.h>
#include<qstring.h>
#undef Unsorted // X headers...
#include<qdir.h>

#include<kconfigbase.h>

#include"dropdlg.h"

#include"qmail.h"
#include"qmailcfg.h"

KQMailDrop::KQMailDrop()
	: KPollableDrop()
{
	_info = new QFileInfo;
	_lastMod = new QDateTime;

	_lastSize = 0;

	_valid = false;
	_maildir = "";
}

KQMailDrop::~KQMailDrop()
{
	stopMonitor();

	delete _info;
	delete _lastMod;
}

void KQMailDrop::recheck()
{
	if( valid() && touched() ) {
		QDir dir( _info->filePath() );

		int messages = (dir.count()-2);

		if( messages != count() ) {
			emit changed(messages);
		}
	}
}

bool KQMailDrop::valid()
{
	if( !_valid ) {
		return false;
	}

	_info->refresh();

	return _info->exists();
}

bool KQMailDrop::touched()
{
	_info->refresh();

	if(_info->size() != _lastSize
			|| (_info->lastModified() > *_lastMod) ) {

		_lastSize = _info->size();
		*_lastMod = _info->lastModified();

		return true;
	}

	return false;
}

void KQMailDrop::setMaildir( const char *dir )
{
        assert( dir );

        bool run = running();

        if( run ) {
                stopMonitor();
        }

	_maildir = dir;

	QString real = dir;
	real += "/new";

	_valid = true;

        // update monitors
        _info->setFile( real );
        _lastMod->setTime_t( 0 );

        if( run ) {
                startMonitor();
        }  	
}

KQMailDrop& KQMailDrop::operator=( const KQMailDrop& other )
{
	setMaildir( other.maildir() );
	setFreq( other.freq() );

	return *this;
}

QWidget* KQMailDrop::typeSpecificConfig()
{
	return 0;
}

KMailDrop* KQMailDrop::clone() const
{
	KQMailDrop *clone = new KQMailDrop;

	*clone = *this;

	return clone;
}

bool KQMailDrop::readConfigGroup( const KConfigBase& cfg )
{
	KPollableDrop::readConfigGroup( cfg );

	QString dir = cfg.readEntry( MaildirConfigKey );

	if( dir.isEmpty() ) {
		warning( "KQMailDrop::readConfigGroup: no dir for '%s'.",
		      caption().ascii() );

		_valid = false;

		return false;
	}

	setMaildir( dir );

	return true;
}

bool KQMailDrop::writeConfigGroup( KConfigBase& cfg ) const
{
	KPollableDrop::writeConfigGroup( cfg );
	cfg.writeEntry( MaildirConfigKey, maildir() );

	return true;
}

void KQMailDrop::addConfigPage( KDropCfgDialog *dlg )
{
	dlg->addConfigPage( new KQMailCfg ( this ) );
	KPollableDrop::addConfigPage( dlg );
}

const char *KQMailDrop::MaildirConfigKey = "maildir";
