#!/usr/bin/perl

use strict;
use warnings;

use Carp qw(confess);
use Data::Dumper;
use Getopt::Std;

use Ernad::Args;
use Ernad::Common;
use Ernad::Editor;
use Ernad::Erimp;
use Ernad::Indat::Report;
use Ernad::Pages;
use Ernad::Store;
use Ernad::Rif;
use Krichel::File;

my %o;
&Getopt::Std::getopts('et', \%o);

my $do_editor = $o{'e'} // 0;
my $do_title = $o{'t'} // 0;
if(not $do_editor and not $do_title) {
  print "I need -e for editor or -t for title\n";
}

our ($impna, $e, $repcode, $in_file);
&Ernad::Args::parse();
if(not $repcode) {
  print "I don't see your report\n";
  exit;
}
$e=Ernad::Erimp->new({'impna'=> $impna, 'verbose'=>3});
my $rerc=$e->{'report'}->{$repcode} // '';
if(not $rerc) {
  print "I don't know about your report '$repcode'.\n";
  exit;
}

my $title_ele;
if($do_title) {
  my $repdoc=$rerc->{'repdoc'} // confess "I need a repdoc here.";
  my $xpc=$e->{'x'}->{'xpc'} // confess 'I need Xpath here.';
  my $xp='/amf:amf/amf:collection/amf:title';
  $title_ele=$xpc->findnodes($xp,$repdoc)->[0] // confess "I need this.";
}

my $sent_dir=$rerc->{'dir'}->{'sent'};
## required to call update_editor_in_doc($rix,$rs);
my $rs;
$rs->{'repcode'}=$repcode;
$rs->{'e'}=$e;
foreach my $file (glob("$sent_dir/*")) {
  #if(not &Ernad::Common::is_rif_name($file)) {
  if(not $e->{'f'}->is($file)) {
    $e->echo(__LINE__,"File $file is not a rif, skip.");
    next;
  }
  my $rif=$file;
  my $rix=&Krichel::File::load($rif);
  if(not $e->{'x'}->count_texts($rix)) {
    $e->echo(__LINE__,"Rif $rif has no texts, skip.");
    next;
  }
  my $issuedate=&Ernad::FileInfo::issuedate($file,'do_strict');
  if($do_editor) {
    $rix=&Ernad::Editor::update_in_doc($rix,$rs);
  }
  if($do_title) {
    #$rix=&Ernad::Rif::change_title($rix,$title_ele);
    $rix=$e->{'x'}->change_title($rix,$title_ele);
  }
  my $out_file=$rerc->{'dir'}->{'blatt'}."/$issuedate.html";
  &Krichel::File::prepare($out_file);
  my $doc=$e->{'t'}->transform($rix,'email_html_issue');
  &Ernad::Pages::install($doc,$out_file);
  $e->echo(__LINE__,"I wrote $out_file.");
}

__END__;
