package flo::plugin::Cache::Reader;
use flo::Standard;
use flo::Object;
use lib::Exception;
use vars qw /@ISA/;
@ISA = qw /flo::Object/;
use strict;

sub main
{
    my $class = shift;
    my $cgi = cgi;
    my $path_info = path_info;
    
    # compute the filename of the potentially cached page
    my $config = general_config;
    my $dir = $config->get ('cache_dir');
    
    my $file_name = $path_info;
    $file_name = '__root__' if ($file_name eq '/');
    $file_name = '__root__' if ($file_name eq '/');
    $file_name =~ s/^\///;
    $file_name =~ s/\/$//;
    $file_name =~ tr/\//_/;
    my $html_file_name = $dir . '/' . $file_name . '.html';
    my $time_file_name = $dir . '/' . $file_name . '.time';
    
    # give up on that query if the file does not exist
    return unless (-e $html_file_name);
    
    # if the time is inferior to the max caching time,
    # then we should return cached data. Otherwise, remove
    # the cached files and pass the query
    open FP, "<$time_file_name" or
	throw (new lib::Exception ( code => 'CANNOT_OPEN_FILE',
				    info => "Could not read-open $time_file_name!" ) );
    my $time = <FP>;
    chomp ($time);
    close FP;
    
    if (time < $time)
    {
	# let's send the data and terminate
	open FP, "<$html_file_name" or
	    throw (new lib::Exception ( code => 'CANNOT_OPEN_FILE',
					info => "Could not read-open $html_file_name!" ) );
	print join '', <FP>;
	close FP;
	return 'TERMINATE';
    }
    else
    {
	# let's remove expired cached files and pass the query
	unlink $html_file_name;
	unlink $time_file_name;
    }
}


1;
