#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV;
use diagnostics;
use Data::Dumper;

my $file = 'Manifest.csv';
my %dates;

open my $CSV, "<:encoding(utf8)", $file or die "$file: $!";

my $csv = Text::CSV->new({ binary => 1,eol => $/ })
  or die "Text::CSV error: " . Text::CSV->error_diag;

### Nathan Added
$csv->column_names ($csv->getline ($CSV));
my $file_contents = $csv->getline_hr_all ($CSV);

foreach my $row (@ {$file_contents})
{
  my $rowref=getFiles($row);
  updateDateHash($rowref) if($rowref->{'found'});
}
## Nathan Added


sub getFiles {
  #Rewrite to take entire row, just as item does.
  #Then add $found to row href, then parse and set dates in href.

  my $row    = shift;
  my $fn     = $row->{"File Name"};            #printf STDERR "fn: %s\n", $fn;
  my $tDir   = $row->{"Target Directory"};     #printf STDERR "tDir: %s\n", $tDir;
  my $sDir   = $row->{"Search Directory"};     #printf STDERR "srcDir: %s\n", $srcDir;
  my $fnCons = $row->{"File Name Constant"};   #printf STDERR "fnCons: %s\n", $fnCons;
  warn "no fnCons for fn: $row->{'File Name'}" if ((!$fnCons) or ($fnCons=~/^\s*$/));

  #For now just replace each # with \\d:
  my $fileMask = $fnCons;
  $fileMask =~s/#/\\d/g; 		       #printf STDERR "re: %s\n", $fileMask;

  if ((!$fileMask) or ($fileMask=~/^\s*$/)) {
    $fileMask = $fn;
    $fileMask=~s/YYYY/\\d{4}/;
    $fileMask=~s/MM/\\d{2}/;
    $fileMask=~s/DD/\\d{2}/;
    $fileMask=~s/HH.*//;
    $fileMask=~s/MI.*//;
    $fileMask=~s/SS.*//;

  }
  printf STDERR "fileMask: %s\n", $fileMask;

  $row->{"File Mask"}=$fileMask;
  saveRe($fileMask);

  return $row if(!$tDir);
  if (! -d $tDir) {
    mkdir $tDir or die $!;
  }

  my @all;

  printf STDERR "searching %s for %s\n", $sDir, $fileMask;

  foreach my $found (`ls $sDir`) {
    chomp $found;

    #Can do this with array offsets for speed?
    next unless ($found =~ $fileMask);
    chop $sDir if $sDir =~/\/$/; #trim trailing slash

    printf STDERR "found %s in %s\n", $found,$sDir;

    my $s="$sDir/$found";
    die "$s not found: $!" unless -f "$s";

    chop $tDir if $tDir =~/\/$/;
    my $t="$tDir/$found";

    printf STDERR "renaming %s to %s\n", $s, $t;
    rename($s, $t) or die $!;
    push (@all, $found);
  }

  ($row->{"found"})=@all;
  return $row;
}

sub saveRe {
  my $line = shift;
  my $histFile = '.regex.history';
  #printf STDERR "saving %s to %s\n", $line, $histFile;
  open my $HF, '>>', $histFile or die "$histFile: $!";
  printf $HF "%s\n", $line;
  close $HF;
}

sub updateDateHash {
  my $rowr = shift;

  my $order = $rowr->{"Order"};
  printf STDERR "order: %s\n", $order;
  die "order not a num: $order" unless $order =~/^\d+$/;
  printf STDERR "order: %s\n", $order;

  my $dc = $rowr->{"Date Convention"};
  if($dc) { printf STDERR "dc: %s\n", $dc; } else { $dc=''; }

  #Can use this to identify type by leading alpha chars:
  my $fmt = $rowr->{"File Name Constant"};
  if($fmt) { printf STDERR "fmt: %s\n", $fmt; } else { $fmt=''; }

  my $found=$rowr->{"found"};
  printf STDERR "found: %s\n", $found;

  if((!$found)||($found=~/^\s*$/)) {
    die "rowr->{found} not found!";
  }

  my($re,$date);

  if (( $dc =~/YYYY-MM-DD/) ||
      ( $fmt =~/[^#]####-##-##[^#]]/ )) {
    my $re="\^.*\(\\d{4}\)-\(\\d{2}\)-\(\\d{2}\).*\$";
    printf STDERR "matching %s to %s\n", $found, $re;
    $date=$found;
    $date=~s/$re/$1-$2-$3/;
    die "no date in $found" unless $date;
  }

  if (( $dc =~/YYYYMMDD/) ||
      ( $fmt =~/[^#]########_######[^#]]/ )) {
    my $re="\^.*\(\\d{4}\)\(\\d{2}\)\(\\d{2}\).*\$";
    printf STDERR "matching %s to %s\n", $found, $re;
    $date=$found;
    $date=~s/$re/$1-$2-$3/;
    die "no date in $found" unless (($date) && ($date!~/^\s*$/));
  }

 if (( $dc =~/MMDDYYYY/) ||
     ( $fmt =~/[^#]############[^#]]/ )) {
   my $re="\^\.*\(\\d{2}\)\(\\d{2}\)\(\\d{4}\).*\$";
    printf STDERR "matching %s to %s\n", $found, $re;
   $date=$found;
   $date=~s/$re/$3-$1-$2/;
   die "no date in $found" unless (($date) && ($date!~/^\s*$/));
 }

  if (( $dc =~/YYYYMMDD/) ||
      ( $fmt=~/[^#]########[^#]/ )) {
    #Ravicti_Dispense_SP002a_20130729.xls
    my $re="\^\.*\(\\d{4}\)\(\\d{2}\)\(\\d{2}\).*\$";
    printf STDERR "matching %s to %s\n", $found, $re;
    $date=$found;
    $date=~s/$re/$3-$1-$2/;
    die "no date in $found" unless (($date) && ($date!~/^\s*$/));
  }

  my $year=substr($date,0,4);
  my $month=substr($date,5,2);
  my $day=substr($date,8,2);

  foreach my $var ($year, $month, $day) {
    warn "not a num: $var" if( $var!~/^\d+$/);
  }

  $dates{$order}->{"found"} = $found;
  $dates{$order}->{"Year"}  = $year;
  $dates{$order}->{"Month"} = $month;
  $dates{$order}->{"Day"}   = $day;

  print Dumper(%dates);
}


__DATA__
'####-##-##',
'############',
'########',
'########_######',
'####-##-##',
'####-##-##',
'####-##-##',
'####-##-##',
'####-##-##',
'####-##-##',
'####-##-##',
'########_######',
'############',
'########',
