#!/usr/bin/perl 

use v5.14;
use warnings;
use Feature::Compat::Try;

use Devel::MAT::Cmd::Terminal;
use Getopt::Long qw( :config no_permute );
use Commandable::Invocation 0.03; # ->new_from_tokens

use constant CAN_COLOUR => -t STDERR;

GetOptions(
   'quiet|q' => \( my $QUIET ),
   'blib'    => sub { require blib; blib->import },
) or exit 1;

# Some tools might want to draw pretty graphs with line drawing / similar
STDOUT->binmode( ":encoding(UTF-8)" );
STDOUT->autoflush(1);

require Devel::MAT;

my $file = shift @ARGV or die "Need dumpfile\n";

my $progress = ( CAN_COLOUR && !$QUIET ?
   sub { print STDERR "\r\e[K" . ( shift // "" ); } :
   undef
);

my $pmat = Devel::MAT->load( $file,
   progress => $progress,
);

$progress->() if $progress;

my $df = $pmat->dumpfile;

if( !$QUIET ) {
   $pmat->run_command( Commandable::Invocation->new( "summary" ) );
}

if( @ARGV ) {
   $pmat->run_command(
      Commandable::Invocation->new_from_tokens( @ARGV ),
      progress => $progress,
   );

   # Finish the pagination output
   Devel::MAT::Tool::more->run while Devel::MAT::Tool::more->can_more;

   exit
}

require Term::ReadLine;

my $rl = Term::ReadLine->new( 'pmat' );
while( defined( my $line = $rl->readline(
         sprintf 'pmat%s> ', Devel::MAT::Tool::more->can_more ? " [more]" : ""
      ) ) ) {
   my $inv = Commandable::Invocation->new( $line );
   defined $inv->peek_token or
      $inv = Commandable::Invocation->new( "more" ) if Devel::MAT::Tool::more->can_more;

   next unless defined $inv->peek_token; # blank line

   last if $inv->peek_token eq "exit" or $inv->peek_token eq "quit";

   try {
      # We just have to hope nobody catches this one.
      # It would be nice to  next COMMAND  but awkward perl internals reasons
      # mean we can't do that from a signal handler
      local $SIG{INT} = sub { die "\nAborted\n"; };

      $pmat->run_command( $inv,
         progress => $progress,
      );
   }
   catch ($e) {
      print STDERR "$e";
   }

   print "\n";
}

print "\n";

=head1 NAME

pmat - Perl Memory Analysis Tool

=head1 SYNOPSIS

   $ pmat my-file.pmat

=head1 OPTIONS

=over 4

=item --quiet, -q

Don't print progress reports or welcome banner.

=back

=head1 DESCRIPTION

See L<Devel::MAT::UserGuide>.

=head1 AUTHOR

Paul Evans <leonerd@leonerd.org.uk>

=cut
