package LastModified;
# $Id: LastModified.pm,v 1.14 2000/12/20 14:59:31 tom Exp $
################################################################

use strict;
use vars qw(@ISA @EXPORT);

use Exporter;
use ObjectTemplate;

@ISA = qw(ObjectTemplate);
@EXPORT = qw(attributes);

attributes qw(lm_file
	      lm updated);

################################################################
sub initialize($)
{
    my $self = shift;

    $self->lm_file("log/LastModified") unless $self->lm_file;
#    $self->GetLastModified;
    $self->updated(0);

    $self->SUPER::initialize;
}
sub SetLastModified($$)
{
    my ($self, $new_lm) = @_;

    my $old_lm = $self->lm;

#    print "content-type: text/html\n\n";
#    print "$old_lm<br>$new_lm";
#    die "$old_lm<br>$new_lm";
    
    if ($old_lm < $new_lm){
#	die $new_lm;
#	warn times, " updated: $old_lm -> $new_lm";
	$self->lm($new_lm);
	$self->update_last_modified_file;
	$self->updated(1);
    }
    return $self->lm;
}
sub GetLastModified($)
{
    my $self = shift;

    unless (ref $self){
	# called as static function
	# such as LastModified::GetLastmodified($file);
	my $filename = $self;
	return (stat($filename))[9];
    }
    my $lm = $self->lm;
    unless ($lm)                {                # no data set
	if (-f $self->lm_file){
#	    warn times, " read l-m file";
	    if (open(F, $self->lm_file)){
		$lm = <F>;
		close(F);
	    }
	    chomp $lm;
#	} else {
#	    $lm = $self->GetRealLastModified;
#	    $self->get_real_last_modified;
#	    $lm = $self->lm;
	}
	$self->lm($lm);
    }
    return $lm;
}
   
sub GetLastModifiedString($;$)
{
    my ($self, $tz) = @_;

    $tz ||= "GMT";

    require DateTime::Format;
    return DateTime::Format::time2str("%a, %d %b %Y %H:%M:%S %Z",
				      $self->GetLastModified, $tz);
}
sub ExistLastModifiedFile($)
{
    my $self = shift;

    return -f $self->lm_file;
}
################################################################
sub update_last_modified_file
{
    my $self = shift;

    my $lm = $self->lm;

    open(F, ">" . $self->lm_file) || die $self->lm_file;
    print(F $lm);
    close(F);
    
    return $self->lm($lm);
}
# should be overriden
#sub GetRealLastModified($)
#{
#    return 0;
#}
    

1;
