package System::Introspector::Report::Publish::MediaWiki::Updater;
use Moo;
use Try::Tiny;
use Module::Runtime qw( use_module );
use Log::Contextual::WarnLogger;
use Log::Contextual qw( :log ),
  -default_logger => Log::Contextual::WarnLogger->new({
    env_prefix => 'SI_REPORT_MEDIAWIKI_UPDATER',
    levels      => [qw( error warn info debug trace )],
  });

has connection => (is => 'ro', lazy => 1, builder => 1, handles => {
  get_page => 'get',
  put_page => 'put',
});

sub _build_connection {
  my ($self) = @_;
  return use_module($self->connection_class)->new(
    api_uri         => $self->api_uri,
    username        => $self->username,
    password        => $self->password,
    allow_create    => 1,
    $self->http_auth ? (
      http_auth  => 1,
      http_realm => $self->http_realm,
    ) : (),
  );
}

sub process {
  my ($self, $stream) = @_;
  while (my $report = $stream->()) {
    $self->_process_page(@$report);
  }
  return 1;
}

sub _process_page {
  my ($self, $page_name, $options, $reports) = @_;
  unless (scalar @$reports) {
    log_debug { "Skipping page '$page_name': No reports to publish" };
    return 1;
  }
  my $do_create = $options->{create};
  return try {
    my $page = $self->get_page($page_name);
    if ($page->is_new and not $do_create) {
      log_trace { "Skipping page '$page_name': Does not yet exist" };
      return 1;
    }
    my $is_changed = $page->update($reports);
    unless ($is_changed) {
      log_debug { "Not pushing page '$page_name': No changes" };
      return 1;
    }
    log_debug { "Updating page '$page_name'" };
    $self->put_page($page);
    return 1;
  }
  catch {
    log_error { "Error during page update: $_" };
    return 1;
  };
}

with $_ for qw(
  System::Introspector::Report::Publish::MediaWiki::HasConnectInfo
);

1;
