#!/usr/bin/perl

use strict;
use warnings;

use Carp qw(confess);
use Data::Dumper;
use Date::Format;
use Statistics::Descriptive;
use Time::Duration;

use Storable;

use Ernad::Common;
use Ernad::Erimp;
use Krichel::String;

my $impna = $ARGV[0] // die "no impna";
#my $count=$ARGV[1] // die "no observation count";

my $total=60;
our $e=Ernad::Erimp->new({'impna' => $impna});
my $home_dir=$e->{'dir'}->{'home'} or die;
my $doc = $e->{'x'}->create_ernad_doc();
my $ernad_element=$doc->documentElement();
my $allport=$e->get_allport_repcode();
my $verbose=1;

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 $tt;
my $times_file="/tmp/editing_times.dump";
## for quicker testing, save the results
if($verbose) {

}
## time taken
if(-f $times_file and -M $times_file < 1) {
  if($verbose) {
    print "I get the times from $times_file\n";
  }
  $tt=retrieve($times_file);
}
else {
  $tt=&get_times();
}

foreach my $repcode (keys %{$tt}) {
  my $median_secs=$tt->{$repcode}->{'median_secs'} or next;
  $tt->{$repcode}->{'median_duration'}=duration($median_secs);
}

my @repcodes = sort{ $tt->{$a}->{'median_secs'} <=> $tt->{$b}->{'median_secs'} } keys %{$tt};

foreach my $repcode (@repcodes) {
  my $report_element=$doc->createElement('report');
  my $result=$tt->{$repcode};
  $report_element->setAttribute('repcode',$repcode);
  $report_element->setAttribute('repcode_pretty',&Krichel::String::dashing($repcode));
  $report_element->setAttribute('median_secs',$result->{'median_secs'});
  $report_element->setAttribute('median_duration',$result->{'median_duration'});
  $report_element->setAttribute('nobs',$result->{'nobs'});
  $ernad_element->appendChild($report_element);
}
my $web_dir=$e->{'dir'}->{'web'};
my $out_file=$web_dir.'/median_composition_time.html';
my $html_doc=$e->{'t'}->transform($doc,'median_composition_time');
$html_doc->toFile($out_file);
# $e->echo(__LINE__,"I write $out_file.",1);


sub get_times {
  my $time_taken;
  my $stats;
  $stats->{$allport} = Statistics::Descriptive::Full->new();
  my $tt;
  foreach my $repcode ($e->list_repcodes()) {
    ## This is a temporary check to skip the allport
    if(not $e->{'conf'}) {
      confess "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;
    }
    if($verbose) {
      print "repcode is $repcode\n";
    }
    ## This is a temporary check to skip the allport
    if(not $e->{'conf'}) {
      confess "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;
    }
    if($e->{'r'}) {
      $e->{'r'}->load($repcode);
    }
    my $sent_dir=$e->{'report'}->{$repcode}->{'dir'}->{'sent'};
    my $created_dir=$e->{'report'}->{$repcode}->{'dir'}->{'created'};
    my $selected_dir=$e->{'report'}->{$repcode}->{'dir'}->{'selected'};
    #my $sent_issues=&Ernad::Common::list_issues_in_dir($sent_dir);
    my $sent_issues=$e->{'d'}->issues($sent_dir);
    my @sent_issuedates=reverse sort keys %{$sent_issues};
    my $count=0;
    while($count<$total and defined($sent_issuedates[$count])) {
      my $stat = Statistics::Descriptive::Full->new();
      my $issuedate= $sent_issuedates[$count];
      my $sent_rif=$e->{'d'}->latest_rif($sent_dir,$issuedate) or die;
      #my $end_time=&Ernad::Common::get_time_from_file_name($sent_rif) or die;
      my $end_time=$e->{'f'}->tist($sent_rif) or die;
      my $created_rif=$e->{'d'}->get_earliest_rif($created_dir,$issuedate);
      my $start_time;
      if(not $created_rif) {
        if($verbose) {
          print "no created rif for $repcode at $issuedate\n";
        }
        my $selected_rif=$e->{'d'}->get_earliest_rif($selected_dir,$issuedate);
        if(not $selected_rif) {
          if($verbose) {
            print "no selected rif for $repcode at $issuedate\n";
          }
          $count++;
          next;
        }
        if($verbose) {
          print "The earliest rif for $issuedate is $selected_rif\n";
        }
        #$start_time=&Ernad::Common::get_time_from_file_name($selected_rif) or die;
        $start_time=$e->{'f'}->tist($selected_rif) or die;
      }
      else {
        #$start_time=&Ernad::Common::get_time_from_file_name($created_rif) or die;
        $start_time=$e->{'f'}->tist($created_rif) or die;
      }
      my $work_time=$end_time-$start_time;
      $stat->add_data($work_time);
      $count++;
      $tt->{$repcode}->{'nobs'}=$count;
      $tt->{$repcode}->{'median_secs'}=$stat->median();
    }
  }
  if($verbose) {
    print Dumper $tt;
    store $tt, $times_file;
  }
  return $tt;
}
