#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;
use Date::Format;

use Ernad::Erimp;
use Ernad::ReportState;
use Krichel::String;

my $impna=$ARGV[0] // '';
if(not $impna) {
  die "no impna";
}

our $e=Ernad::Erimp->new({'impna'=>$impna});
my @repcodes=$e->list_repcodes();

my $home_dir=$e->{'dir'}->{'home'} or die "I have no home directory.";
#my $web_dir=$e->{'dir'}->{'web'};
my $doc = $e->{'x'}->create_ernad_doc();
my $ernad_element=$doc->documentElement();

my $public_time_format=$e->{'conf'}->{'public_time_format'} or
  die "I can't find a public date format";
my $up_date=time2str($public_time_format,time());
$ernad_element->setAttribute('last_update',$up_date);

my $update;
$e->update_last_updates();
foreach my $repcode ($e->list_repcodes()) {
  ## this is really for most basic security
  if(not $e->{'conf'}) {
    die "I need this here.";
  }
  ## this is temporary, as list_repcodes may have the allport
  if($e->{'conf'}->{'allport_repcode'} and $repcode eq $e->{'conf'}->{'allport_repcode'}) {
    next;
  }
  my $rerc=$e->{'report'}->{$repcode};
  $update->{$repcode}->{'tist'}=$rerc->{'update_tist'} or next;
    # or die "I have no update tist for $repcode.";
  $update->{$repcode}->{'pretty'} = time2str($public_time_format,
                                             $rerc->{'update_tist'});
}

foreach my $repcode (keys %$update) {
  if(not $update->{$repcode}->{'tist'}) {
    delete $update->{$repcode};
  }
}

@repcodes = sort{ $update->{$a}->{'tist'} <=> $update->{$b}->{'tist'} } keys %$update;

foreach my $repcode (@repcodes) {
  my $report_element=$doc->createElement('report');
  $report_element->setAttribute('name',&Krichel::String::dashing($repcode));
  ## for some reason this has an extra blank
  #  chop $las{$repcode};
  $report_element->setAttribute('time',$update->{$repcode}->{'tist'});
  $report_element->setAttribute('date',$update->{$repcode}->{'pretty'});
  $ernad_element->appendChild($report_element);
}
$doc->setDocumentElement($ernad_element);
my $web_dir=$e->{'dir'}->{'web'};
my $out_file=$web_dir.'/last_action.html';
my $html_doc=$e->{'t'}->transform($doc,'last_action');
$html_doc->toFile($out_file);
