use utf8;
use strict;
use warnings; no warnings "redefine";

=head1 Debug-Modus

Durch Angabe einer whitespace-getrennten Liste der von L<Template> unterstützten
Debug-Flags (vgl. L<Template::Manual::Config/DEBUG>) in der Environment-Variable
TEMPLATE_DEBUG kann man die entsprechenden Debug-Modi aktivieren.
Das Präfix C<DEBUG_> kann dabei jeweils weggelassen werden, sprich
C<TEMPLATE_DEBUG=ALL> ist dasselbe wie C<TEMPLATE_DEBUG=DEBUG_ALL>.

=cut

my @additional_args;
if ( $ENV{TEMPLATE_DEBUG} ) {
	require Template::Constants and Template::Constants->import(':debug');
	push @additional_args,
	  DEBUG => eval join '|',
	  map /^DEBUG_/ ? uc : "DEBUG_\U$_", split ' ', $ENV{TEMPLATE_DEBUG};
	die $@ if length $@;
}

sub process_template($;$$) {
	my ( $data, $template, $output ) = @_;
	if ( defined $template ) {
		require Template;
		my $t =
		  Template->new( { ABSOLUTE => 1, RELATIVE => 1, @additional_args } )
		  or die;
		$t->process( $template, $data, $output ) or die $t->error;
	}
	else {
		require Data::Dumper;
		my $dump =
		  Data::Dumper->new( [$data], ['*template_data'] )->Indent(1)->Sortkeys(1)->Dump;

		# Die nächste Zeile verwandelt die Escapecodes, die Data::Dumper
		# manchmal (nicht immer!) verwendet, wieder in was Vernünftiges.
		$dump =~ s/\\x\{([0-9a-f]+)\}/chr(hex($1))/eig;

		unless ( defined $output ) { print $dump }
		elsif ( 'SCALAR' eq ref $output ) { $$output .= $dump }
		else { print $output $dump }
	}
}

1;
