#!perl
use Encode;
use Encode::Locale;
use IO::Interactive qw/is_interactive/;
use POSIX qw/EXIT_SUCCESS/;
use MarpaX::Languages::M4::Impl::Default;
use Log::Any;
use Log::Any::Adapter;
use Log::Any::Adapter::Callback;

# ABSTRACT: M4 implementation in Perl

our $VERSION = '0.006'; # VERSION

our $AUTHORITY = 'cpan:JDDPAUSE'; # AUTHORITY

# PODNAME: m4pp

#
# Get the numbers associated to levels
#
my @logging_methods = Log::Any->logging_methods;
my $i = -1;
my %logging_levels = map {++$i; $logging_methods[$i] => $i} (0..$#logging_methods);
#
# Set logger
#
Log::Any::Adapter->set('Callback', min_level => 'trace', logging_cb => \&_logging_cb);
#
# Call implementation
#
my $impl = MarpaX::Languages::M4::Impl::Default->new_with_options();
print $impl->impl_value;
exit($impl->impl_rc);

sub _logging_cb {
  my ($method, $self, $format, @params) = @_;

  my $level = $logging_levels{$method};
  print STDERR "$format @args\n";
  #
  # If level is >= error, then check debugfile
  #
  if (! defined($level)) {
    return;
  }
  my $fh;
  open($fh, '>>&STDERR');
  my $fhName = 'STDERR';
  if ($level >= $logging_levels{error}) {
    #
    # If called within new_with_options(), $impl
    # is not yet setted
    #
    my $thisSelf = $impl || $MarpaX::Languages::M4::SELF;
    print STDERR "\$thisSelf = " . (defined($thisSelf) ? $thisSelf : '<undef>') . "\n";
    my $debugfile = $thisSelf->impl_debugfile;
    if (defined($debugfile)) {
      if (! open($fh, '>>', $debugfile)) {
        #
        # Hmmm...
        #
        warn "Cannot open $debugfile, $!";
        $fh = \*STDERR;
      } else {
        $fhName = $debugfile;
      }
    }
  }
  if ($ENV{M4_ENCODE_LOCALE}) {
    binmode $fh, ":encoding(console_out)" if (is_interactive($fh));
  }

  printf $fh $format, @params;
  if (! close($fh)) {
    warn "Cannot close $fhName, $!";
  }
}

exit(EXIT_SUCCESS);

__END__

=pod

=encoding UTF-8

=head1 NAME

m4pp - M4 implementation in Perl

=head1 VERSION

version 0.006

=head1 AUTHOR

Jean-Damien Durand <jeandamiendurand@free.fr>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by Jean-Damien Durand.

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
