#!/usr/bin/perl

use strict;
use warnings;

use Carp qw(cluck longmess shortmess croak confess);
use File::Path;
use Data::Dumper;
use List::Util qw(shuffle);
use Statistics::Descriptive;

use Ernad::Common;
use Ernad::Constant;
use Ernad::Files;
use Ernad::Erimp;
#use Ernad::Eval::Lunol;
use Ernad::Learn;
use Krichel::File;

my $verbose=1;

my $type='model';

my $impna=$ARGV[0];
if(not defined($impna)) {
  die "I need the impna.";
}
my $l=Ernad::Learn->new({'impna' => $impna,
                         'verbose' => 1});
if(not $l) {
  die "You gave me an invalid impna $impna\n";
}
my $e=$l->{'e'};

## do only one repcode
my $only_do_repcode=$ARGV[1] // '';

my $model_dir=$e->{'dir'}->{'learn'}.'/model';
if(not -d $model_dir) {
  mkpath $model_dir;
}

my $eval_web_dir=$e->{'dir'}->{'eval_web'} or die "eval_web_dir not set in ernad.conf";
if(not $eval_web_dir) {
  confess "I can't find the eval_web_dir $eval_web_dir";
}
my $style_file=$e->{'dir'}->{'style'}.'/'.$type.$e->{'const'}->{'xsl_ext'};
if(not $style_file) {
  confess "I can't find the style_file $style_file";
}

## the all_handle_cache
my $a_h_c;

my $ernad_ns=$Ernad::Constant::c->{'ernad_ns'};
my $name='models';

my @repcodes=shuffle $e->list_repcodes();
if($only_do_repcode) {
  &work_on_report($only_do_repcode);
}
else {
  foreach my $repcode (@repcodes) {
    &work_on_report($repcode);
  }
}

sub work_on_report {
  my $repcode=shift // confess "I need a repcode here.";
  my $out_file="$model_dir/$repcode.xml";
  my $models_element;
  my $doc;
  if(-f $out_file) {
    $doc=&Krichel::File::load($out_file);
    $models_element=$doc->getElementsByTagNameNS($ernad_ns,'models_evaluation')->[0];

  }
  else {
    $doc=$e->{'x'}->get_ernad_doc();
    $models_element=$doc->createElementNS($ernad_ns,'models');
    $models_element->setAttribute('repcode',$repcode);
    $doc->documentElement->appendChild($models_element);
  }
  #$e->update_collection_in_doc($doc,$repcode);
  $e->{'x'}->update_collection_in_doc($doc,$repcode);
  &get_eval($repcode,$doc);
  &Ernad::Files::save_xml_with_temp($out_file,$doc);
}

sub get_eval {
  my $repcode=shift;
  my $doc=shift;
  my $count_get=0;
  my $mocla_dir=$l->{'mocla_dir'}.'/'.$repcode;
  my $model_glob="$mocla_dir/*.model";
  print Dumper $model_glob;
}
