#!/usr/bin/env raku

use Test;
use lib 'lib';

constant DEBUG = %*ENV<APP_LOREA_DEBUG>;
constant INCLUDE = $*REPO.repo-chain.map: *.path-spec;

for (
    'Happy output to STDOUT',
    ( '--regex', 'lorea\-test', '--', $*EXECUTABLE, '-e', 'True.say' ),
    'True', '',

    'Happy output to STDERR',
    ( '--regex', 'lorea\-test', '--', $*EXECUTABLE, '-e', 'True.note' ),
    '', 'True',

    'Must provide arguments',
    ( '--regex', 'lorea\-test' ),
    'Usage:', '',
) -> $msg, @args, $out, $err {
    with new-file() {
       .&run(@args).&is: { :$out, :$err }, $msg;
       try .unlink;
    }
}

done-testing;

sub run ( $path, *@args ) {
    if DEBUG {
        for @args {
            FIRST diag 'Running command with:';
            diag "* $_";
            LAST diag '----';
        }
    }

    my $proc = Proc::Async.new:
        $*EXECUTABLE, '-I' «~« INCLUDE, './bin/lorea', |@args;

    my Str $out = '';
    my Str $err = '';

    react {
        whenever $proc.stdout.lines {
            diag "OUT: $_" if DEBUG;
            $out ||= $_;
            $proc.kill;
        }
        whenever $proc.stderr.lines {
            diag "ERR: $_" if DEBUG;
            $err ||= $_;
            $proc.kill;
        }
        whenever $proc.ready {
            diag 'Started' if DEBUG;
        }
        whenever $proc.start {
            diag 'Finished' if DEBUG;
            done;
        }
        whenever Supply.interval: .4 {
            diag "Triggering change on $path" if DEBUG;
            $path.spurt: 'ping';
        }
        whenever Promise.in: 10 {
            diag 'Timeout' if DEBUG;
            $proc.kill;
        }
    }

    return { :$out, :$err }
}

sub new-file {
    my $filename = 't'.IO.child: 'lorea-test-' ~ ( ^10 ).pick(*).join;
    diag "Using $filename..." if DEBUG;
    $filename;
}
