package TM::GitLab::Mojo::Plugin::Worker;
use Mojo::Base 'Mojolicious::Plugin';

#use EV;
#use AnyEvent::Open3::Simple;
#use AnyEvent;
use Mojo::IOLoop::ForkCall;

sub register {
    my ($self, $app) = @_;

    $app->minion->add_task(shout => \&_shout);
}

sub _shout {
    my $job = shift;
    my $app = $job->app;
    my $log = $app->log;

    my $delay = Mojo::IOLoop::Delay->new;
    $log->debug("yay: $$ ". ref($delay));

    my $end = $delay->begin;

    my $fc = Mojo::IOLoop::ForkCall->new;
    $fc->run(
        sub {
            exec('echo "hai" > TEST_FILE');
            exit(1); # if exec failed
        },
        [],
        sub {
            use Data::Dumper;
            $log->debug(Dumper(\@_));
            $end->();
        }
    );

#    my $ipc = AnyEvent::Open3::Simple->new(
#        on_start => sub {
#            my ($proc, $program, @args) = @_;
#
#            $log->debug("started command $program with pid: ". $proc->pid);
#        },
#        on_stdout => sub {
#            my ($proc, $line) = @_;
#            $log->debug("[stdout] $line");
#        },
#        on_stderr => sub {
#            my ($proc, $line) = @_;
#            $log->debug("[stderr] $line");
#        },
#        on_exit => sub {
#            my ($proc, $exit_value, $signal) = @_;
#
#            $log->debug("finished: $exit_value");
#            $end->();
#        },
#        on_error => sub {
#            my ($error, $program, @args) = @_;
#            $log->error("yayks: $error");
#            $end->();
#        }
#    );

#    $ipc->run('echo "hello" > TEST_FILE');
}

42;
