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

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

has _known_package => (is => 'ro', default => sub { {} });
has _host_package  => (is => 'ro', default => sub { {} });
has _host_upgrade  => (is => 'ro', default => sub { {} });

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

sub _collect_from_data {
  my ($self, $id, $hostname, $packages, $upgrade, $data) = @_;
  for my $package (keys %$packages) {
    $self->_known_package->{$package}++;
  }
  $self->_host_package->{$id} = $packages;
  $self->_host_upgrade->{$id} = $upgrade;
  return 1;
}

sub render_reports {
  my ($self) = @_;
  my @columns = (
    { key => 'package', label => 'Package' },
    { key => 'version', label => 'Version' },
    { key => 'upgrade', label => 'Upgrade' },
  );
  my $host_package = $self->_host_package;
  my $host_upgrade = $self->_host_upgrade;
  my @known_packages = sort keys %{$self->_known_package};
  return map {
    my $remote = $_;
    +{
      columns => \@columns,
      title => "Packages on $remote",
      id => ['packages-apt-by-remote', $remote],
      meta => { remote => $remote },
      rows => [map {
        my $package = $_;
        my $version = $host_package->{$remote}{$package}{version};
        my $upgrade = $self->_clear_upgrade(
          $host_upgrade->{$remote}{$package},
          $version,
        );
        +{
          package => $package,
          defined($version) ? (version => $version) : (),
          defined($upgrade) ? (upgrade => $upgrade) : (),
        };
      } @known_packages],
    };
  } sort keys %{$self->_host_package};
}

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

1;
