#===================================================================
# parses sms.csv PDS log; supply optional arg 'from' date yyyy-mm-dd
#===================================================================

use IO::All;
use Data::Dumper;
use FindBin qw($Bin); # warn $Bin;
use DateTime::Format::MySQL;

use strict;

my $src = $Bin . '/sms.csv';
my @rows = io($src)->chomp->slurp; # warn Dumper \@rows;

my $begin; # derived from optional ARGV date
eval {
	if ( my $str = $ARGV[0] ) {
		$begin = DateTime::Format::MySQL->parse_date($str); # optional begin date
	}
}; # warn $begin;
die $@ if $@;

my (%t, %date);
my $i = 0; # row counter - increments if row not skipped

ROW: 
for (@rows) {
	next unless /\A(\d{4}-\d{2}-\d{2})/; # eg header row
	
	if ($begin) { # if 'begin' date supplied
		@date{ qw/year month day / } = split '-', $1; # clobber %date with new vals
		next ROW if DateTime->compare( DateTime->new(%date), $begin ) < 0; # ie row before begin date
	}

	$i++;
	# fix for junk like: "bloggs,":
	$_ =~ s/,//g if $_ =~ /\"[A-Za-z]\"/;
	my ($code, $time) = ( split /\,/ )[12, -1]; # warn Dumper [$code, $time];

	$t{code}{$code}++;
	$t{time} += $time;
} # warn Dumper $t{code}; exit;

my %demog = map { split ': ' } <DATA>; # don't need chomp if $demog{$_} at end of output

printf "%11s %5s (%.1f%) %s", # code, count, %, decode(contains new-line)
	$_, $t{code}{$_}, 100 * $t{code}{$_} / $i, $demog{$_} || "[unknown code]\n"
		for sort { $t{code}{$b} <=> $t{code}{$a} } keys %{ $t{code} };
printf "\nAverage response time: %.2f seconds for %s rows\n", $t{time} / $i, $i;

__DATA__
DEMOG-0001: No Match
DEMOG-0007: Multiple matches found
DEMOG-0017: Superceding NHS number returned
DEMOG-0022: NHS Number of response record has been invalidated
DEMOG-0040: NHS number not verified
DEMOG-0042: NHS Number is not a new style number
DEMOG-9999: Generic Spine Service Error
SMSP-0000: Success
SMSP-0001: Input message validation error
SMSP-0002: Response message validation error
SMSP-0003: Data returned from local store, Spine unavailable
SMSP-9999: Generic Spine Mini Service Provider software failure
