# Copyright 2003 Stepan Riha. This code cannot be redistributed without
# permission from www.nonplus.net.
#
# Based on MT 2.64 MT::Template::Context::_hdlr_include
# Copyright Six Apart
#
# Version History
#
#	1.1 - June 9 2003
#	Fixed "Subroutine _hdlr_include redefined" warning
#
#	1.0 - June 4 2003
#	Initial release
#

use strict;
use warnings;
require MT::Template::Context;
package MT::plugins::MTFastIncludeVersion;

my $VERSION = '1.1';

MT::Template::Context->add_tag(FastIncludeVersion => sub { $VERSION } );

# Compiled template module tokens
my %MODULES_CACHE = ();
# Loaded file contents
my %FILES_CACHE = ();

# Override the built-in MT::Template::Context::_hdlr_include function
no warnings 'redefine';
*MT::Template::Context::_hdlr_include = sub {
    my($ctx, $arg, $cond) = @_;
    if (my $tmpl_name = $arg->{module}) {
		my $key = $ctx->stash('blog_id') . ":$tmpl_name";
		my $build = $ctx->stash('builder');
		my $tokens = $arg->{no_cache} ? undef : $MODULES_CACHE{$key};
		if(!$tokens) {
			require MT::Template;
			my $tmpl = MT::Template->load({ name => $tmpl_name,
											blog_id => $ctx->stash('blog_id') })
				or return $ctx->error(MT->translate(
					"Can't find included template module '[_1]'", $tmpl_name ));
			$tokens = $build->compile($ctx, $tmpl->text) or
				return $tmpl->error(MT->translate(
					"Parse error in template '[_1]': [_2]",
					$tmpl->name, $build->errstr));
#			warn "Caching '$tmpl_name'";
			$MODULES_CACHE{$key} = $tokens unless $arg->{no_cache};
		} else {
#			warn "Reusing '$tmpl_name'";
		}

		defined(my $res = $build->build($ctx, $tokens, $cond)) or
			return $ctx->error(MT->translate(
				"Build error in template '[_1]': [_2]",
				$tmpl_name, $build->errstr));
		return $res;
		
    } elsif (my $file = $arg->{file}) {
		my $key = $ctx->stash('blog_id') . ":$file";
		my $c = $arg->{no_cache} ? undef : $FILES_CACHE{$key};
		if(!defined($c)) {
			my $blog = $ctx->stash('blog');
			my @paths = ($file, map File::Spec->catfile($_, $file),
								$blog->site_path, $blog->archive_path);
			my $path;
			for my $p (@paths) {
				$path = $p, last if -e $p && -r _;
			}
			return $ctx->error(MT->translate(
				"Can't find included file '[_1]'", $file )) unless $path;
			local *FH;
			open FH, $path
				or return $ctx->error(MT->translate(
					"Error opening included file '[_1]': [_2]", $path, $! ));
			$c = '';
			local $/; $c = <FH>;
			close FH;
			$FILES_CACHE{$key} = $c unless $arg->{no_cache};
		}
        return $c;
    }
};

1;
