#!/usr/bin/perl

use strict;
use warnings;

use Devel::MAT;
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 ),
) or exit 1;

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

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->load_tool_for_command( "summary" )
      ->run_cmd( Commandable::Invocation->new( "" ) );
}

if( @ARGV ) {
   my $cmd = shift @ARGV;

   $pmat->load_tool_for_command( $cmd,
      progress => $progress,
   )->run_cmd( Commandable::Invocation->new_from_tokens( @ARGV ) );

   # 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 );
   my $cmd = $inv->pull_token;
   $cmd //= "more" if Devel::MAT::Tool::more->can_more;

   next unless defined $cmd; # blank line

   last if $cmd eq "exit";

   eval {
      # 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->load_tool_for_command( $cmd,
         progress => $progress,
      )->run_cmd( $inv );
      1;
   } or
      print STDERR "$@";

   print "\n";
}

print "\n";
