#!/usr/bin/env raku

use Test;

my $tmux = qx[which tmux] or plan :skip-all('tmux not found, skipping capture tests');

chdir $?FILE.IO.dirname;

sub show-diffs(@out,@want) {
  if @out != @want {
    diag "counts differ: { @out.elems } vs { @want.elems }";
    return;
  }
  for (@out Z, @want) -> $p {
    my $line = ++$;
    say "$line differs: " ~ $p[0].raku ~ " vs " ~ $p[1].raku if $p[0] ne $p[1];
  }
}


sub run-example($eg) {
  my $file = "/tmp/done.$*PID";
  my $p = Proc::Async.new: <tmux -C new -x 40 -y 20>, :w;
  my @out;
  $p.stdout.tap: { @out.push: $_ for .lines; }
  my $promise = $p.start;
  $p.put: "send-keys 'export PS1=:' enter";
  $p.put: "send-keys 'raku -I../lib -Itlib in/$eg.raku $file' enter";
  for 1..10 {
   sleep 1;
   last if $file.IO.e;
   diag "waiting for $eg ($file)";
  }
  @out = ();
  $p.put: "capture-pane -p -J";
  sleep 1;
  my @captured = @out;
  unlink $file;
  $p.put: "send-keys exit";
  $p.put: "send-keys enter";
  $p.close-stdin;
  #diag 'waiting for process';
  await $promise;
  my $b = @captured.grep(:k, { .starts-with('%begin') }).tail;
  without $b {
    diag 'capture failed';
    diag @out.raku;
    return Nil;
  }
  my $end = @captured.grep(:k, { .starts-with('%end') }).tail;
  #diag "$b to $end";
  @captured[$b ^..^ $end];
}

for <01-clear 02-scroll 03-scroll-move> -> $test-file {
  my @out = run-example($test-file);
  ok @out, 'capture worked';
  my @want = "out/$test-file".IO.lines;
  $_ .= trim for @out;
  $_ .= trim for @want;
  @out.pop while @out.tail.chars == 0;
  @want.pop while @want.tail.chars == 0;
  is-deeply @out,@want, "match for $test-file" or show-diffs(@out,@want);
}

done-testing;
# vim: syn=perl6
