package System::Introspector::Report::Builder::Perls;
use Moo;

extends 'System::Introspector::Report::Builder';

has skip_errors => (is => 'ro', default => sub { 1 });

has _rows => (is => 'ro', default => sub { [] });

sub required_data {
  return qw(
    perls
    host
  );
}

sub collect_from {
  my ($self, $id, $data) = @_;
  my $perls    = $data->{perls}{perls} || {};
  my $hostname = $data->{host}{hostname};
  if (my @perl_keys = sort keys %$perls) {
    for my $perl_key (@perl_keys) {
      my $perl = $perls->{$perl_key};
      next if defined($perl->{__error__}) and $self->skip_errors;
      push @{$self->_rows}, {
        hostname => $hostname,
        remote   => $id,
        location => $perl->{executable},
        version  => $perl->{config}{version},
        defined($perl->{__error__})
          ? (__error__ => $perl->{__error__})
          : (),
      };
    }
  }
  else {
    push @{$self->_rows}, {
      hostname => $hostname,
      remote   => $id,
    };
  }
  return 1;
}

sub render_reports {
  my ($self) = @_;
  return +{
    title => 'Perl Installations',
    id => 'perls',
    rowid => [qw( remote location )],
    meta => {},
    columns => [
      { key => 'remote',   label => 'Remote' },
      { key => 'hostname', label => 'Hostname' },
      { key => 'location', label => 'Location' },
      { key => 'version',  label => 'Version' },
    ],
    rows => $self->_rows,
  };
}

1;
