package Tak::REPL;

use Term::ReadLine;
use Moo;

has world => (is => 'ro', required => 1);

has remote => (is => 'lazy');

sub _build_remote {
  my ($self) = @_;
  my $world = $self->world;
  $world->remote_for('meta')->blocking_request(
    register => eval => 'Tak::EvalService'
  );
  $world->remote_for('eval')
}

sub run {
  my $remote = $_[0]->remote;
  my $read = Term::ReadLine->new('REPL');

  while (1) {
    my $line = $read->readline('re.pl$ ');
    last unless defined $line;
    next unless length $line;
    my @reply = $remote->blocking_request(eval => $line);
    if ($reply[0] eq 'MISTAKE') {
      die "Botch: ".join(': ', @reply[1,2]);
    }
    my $ret = $reply[1];
    print $ret->{return};
    if ($ret->{stdout}) {
      chomp($ret->{stdout});
      print "STDOUT:\n${\$ret->{stdout}}\n";
    }
    if ($ret->{stderr}) {
      chomp($ret->{stderr});
      print "STDERR:\n${\$ret->{stderr}}\n";
    }
  }
}

1;
