package System::Introspector::Report::Builder::Packages::Apt::ByPackage;
use Moo;

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

has _host_by_remote => (is => 'ro', default => sub { {} });
has _host_data      => (is => 'ro', default => sub { {} });

sub required_data {
  return qw(
    packages/apt
    host
  );
}

sub _collect_from_data {
  my ($self, $id, $hostname, $packages, $upgrades) = @_;
  $self->_host_by_remote->{$id} = $hostname;
  for my $package (keys %$packages) {
    my $version = $packages->{$package}{version};
    my $upgrade = $self->_clear_upgrade($upgrades->{$package}, $version);
    $self->_host_data->{$package}{$id} = {
      version => $version,
      defined($upgrade) ? (upgrade => $upgrade) : (),
    };
  }
}

sub render_reports {
  my ($self) = @_;
  my @columns = (
    { key => 'hostname', label => 'Hostname' },
    { key => 'remote',   label => 'Remote' },
    { key => 'version',  label => 'Version' },
    { key => 'upgrade',  label => 'Upgrade' },
  );
  my $data = $self->_host_data;
  my $hbr  = $self->_host_by_remote;
  return map {
    my $package = $_;
    my $hosts   = $data->{$package};
    +{
      columns => \@columns,
      title => "$package Installations",
      id => ['packages-apt-by-package', $package],
      rowid => [qw( remote )],
      meta => { package => $package },
      rows => [ map {
        my $remote  = $_;
        +{
          remote    => $remote,
          hostname  => $hbr->{$remote},
          %{$hosts->{$remote}},
        };
      } sort keys %$hosts ],
    };
  } sort keys %$data;
}

with $_ for qw(
  System::Introspector::Report::Builder::Packages::Apt::API
);

1;
