package Shotenjin::Embedder;
BEGIN {
  $Shotenjin::Embedder::VERSION = '0.06';
} 

# ABSTRACT: embedd and escape template content
 
use strict;
use warnings;

use Path::Class;


my $GENERATED = '/* GENERATED BY SHOTENJIN HELPER, DO NOT MODIFY DIRECTLY */';
my $GENERATED_QUOTED = quotemeta $GENERATED;



sub process_dir {
    my ($self, $dir, $strip_whitespace, $base_dir) = @_;
    
    dir($dir)->recurse( callback => sub {
        my ($file) = @_;
        
        $self->process_file($file, $strip_whitespace, $base_dir) if -f $file;
    } )
}


sub process_file {
    my ($self, $file, $strip_whitespace, $base_dir) = @_;
    
    my $content = file($file)->slurp . "";
    
    my $res = $self->process_string($content, $strip_whitespace, $base_dir || file($file)->dir);
    
    if ($content ne $res) {
        my $fh = file($file)->openw();
        print $fh $res;
        $fh->close();
        
        print "UPDATED: $file\n";
    }
}


sub process_string {
    my ($self, $content, $strip_whitespace, $base_dir) = @_;
    
    my $content_copy        = $content;
    
    pos $content = 0;
    
    while ($content =~ m!
        ^(
          
            (
            
                ([\t\f ]*) /\*tj  (.*?)  tj(?:file)?\*/  
            )
            
            (?:\s+$GENERATED_QUOTED\s+sources\s:\s'.*?'\s*)?
        )$
    !msgx) {
        
        my $overall             = $1;
        my $overall_quoted      = quotemeta $overall;
        
        my $whitespace          = $3;
        my $directive           = $2;
        my $template            = $4;
        
        my $is_from_file        = $template =~ m/^file\(  (.+?)  \)$/mx;
        
        if ($is_from_file) {
            
            my $from_file = file($1)->absolute( dir($base_dir) );
            
            $template = -e $from_file ? $from_file->slurp : "File [$from_file] not found";
        } 
        
        # removing leading and trailing whitespace
        $template       =~ s/^\s*(.*?)\s*$/$1/mg if $strip_whitespace;
#        $template       =~ s/^[\t\f ]*(.*?)[\t\f ]*$/$1/mg;
        
        # escaping \, new-lines and '
        $template       =~ s!\\!\\\\!g;
        $template       =~ s!\r?\n!\\n!g;
        $template       =~ s!'!\\'!g;
        
        $content_copy   =~ s!$overall_quoted!${directive}\n\n$whitespace$GENERATED\n${whitespace}sources : '$template'!ms;
    }
   
    return $content_copy;
}



__END__
=pod

=head1 NAME

Shotenjin::Embedder - embedd and escape template content

=head1 VERSION

version 0.06

=head1 AUTHOR

Nickolay Platonov <nplatonov@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2011 by Nickolay Platonov.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut

