package LIMS::Validate::DatePlugin;

# from lyo.kato@gmail.com

use strict;
use warnings;

use FormValidator::Simple::Constants;
use FormValidator::Simple::Exception;
use Data::Dumper;
use DateTime; DateTime->DefaultLocale('en_GB'); # set default locale
use Date::Calc;

# will return true if day,month,year params > reference date passed as 2nd arg
sub DATE_GREATER_THAN {
    my ($self, $params, $args) = @_; # warn Dumper ($params, $args);
    my ($year, $month, $day) = @$params;

    my $target = $args->[0];

    return FALSE unless $target->isa('DateTime');
    return FALSE unless Date::Calc::check_date($year, $month, $day);

    my $date = DateTime->new(year => $year, month=> $month, day=>$day);
    return ($date - $target)->is_positive ? TRUE : FALSE;
}

# will return true if day,month,year params < reference date passed as 2nd arg
sub DATE_LESS_THAN {
    my ($self, $params, $args) = @_; # warn Dumper ($params, $args);
    my ($year, $month, $day) = @$params;

    my $target = $args->[0];

    return FALSE unless $target->isa('DateTime');
    # Date::Calc::check_date() doesn't always catch errs eg yr = 19.7
    # return FALSE unless Date::Calc::check_date($year, $month, $day);

    my $date; # eval in case datetime object creation fails (but already validated):
    eval { $date = DateTime->new(year => $year, month => $month, day => $day) };
    return FALSE if $@;

    return ($target - $date)->is_positive ? TRUE : FALSE;
}

1;
