package System::Introspector::Processes;
use Moo;

sub gather {
    my ($self) = @_;
    my $pipe = $self->_open_ps_pipe;
    my $spec = <$pipe>;
    $spec =~ s{(?:^\s+|\s+$)}{}g;
    my @fields = map lc, split m{\s+}, $spec;
    my @rows;
    while (defined( my $line = <$pipe> )) {
        chomp $line;
        $line =~ s{(?:^\s+|\s+$)}{}g;
        my @values = split m{\s+}, $line, scalar @fields;
        my %row;
        @row{ @fields } = @values;
        push @rows, \%row;
    }
    return \@rows;
}

# args is automatically included, since it has to be last
my @Included = qw(
    blocked
    c
    class
    cputime
    egid egroup
    etime
    euid euser
    fgid fgroup
    flags
    fuid fuser
    ignored
    lwp
    nice
    nlwp
    pgid pgrp
    pid ppid
    pri
    psr
    rgid rgroup
    rss
    ruid ruser
    sgid sgroup
    sid
    size
    start_time
    stat
    suid suser
    tid
    time
    tname
    wchan
);

sub _open_ps_pipe {
    my ($self) = @_;
    my $command = sprintf 'ps -eo %s', join(',', @Included, 'args');
    open my $pipe, '-|', $command
        or die "Unable to open pipe to '$command': $!\n";
    return $pipe;
}

1;
