#------------------------------------------------------------
# Copyright (C) 2007 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
#
#------------------------------------------------------------
# Validation Rule Date Object.  Extends the Validate Rule
# class.  This object contains the method to do validation
# on piece of data.
#
# Test if aa string represents a valid date.
#
# Parameter Requirements:
#
#    The parameter used in config_rule must be a:
#       A string representing a date]
#
#       i.e. yyyy/mm/dd
#
# Base Class:
#   Validation::Rule
#
# Public methods:
#   + Validate::Rule::Code new();
#   + $fail_status         ok();
#   + $scalar              AUTOLOAD( $scalar );
#------------------------------------------------------------
package Validate::Rule::Constraint::Date;
use strict;

use Date::Simple;

use lib '/app/tools/common/lib';
use Common::Log;
use Common::RSApp;
use Common::Assert;

use lib '/app/tools/metadata/lib';
use base 'Validate';
use base 'Validate::Rule';

use Validate::Util qw( is_integer );

use vars qw($AUTOLOAD);

###
# Define addition public accessors
###
use constant kClassAttributes => qw( message fail_status parameter );

###
# Default failure message if the OK method fails.
###
use constant kFailureMessage => "Invalid date, format must be YYYY/MM/DD";

#------------------------------------------------------------
# Public Methods
#------------------------------------------------------------

#------------------------------------------------------------
# Constructor
#------------------------------------------------------------
sub new {
    my ( $class, %args ) = @_;
    my $self = bless {}, $class;

    return $self->_init(%args);
}

#------------------------------------------------------------
# $scalar AUTOLOAD( $scalar )
#
# Accessor methods for this object.  Methods to access the
# private data in this object.  Valid members are defined in
# the kClassAttributes constant.
#
# If a scalar is passed in this method will set the
# corrisponding private data member.
#
# This method always returns the value of the corrisponding
# private data member.
#
# This method is almost identical base class AUTOLOAD method
# except the method calls the parent AUTOLOAD instead of
# dying when an unknown attribute was seen.
#
# Parameters:
#   $scalar - Set the private data member to this value.
#             ** optional **
#
# Return:
#   $scalar - private memeber value
#------------------------------------------------------------
sub AUTOLOAD {
    my $self  = shift;
    my $value = shift;
    my $field = $AUTOLOAD;
    $field =~ s/.*://;    # Strips fully-qualified portion.

    my $attr = "_$field";

    return if $field eq 'DESTROY';    # skip DESTROY and all-cap methods

    unless ( $self->{_attributes}->{$field} ) {
        my $superior = "SUPER::$field";
        $self->$superior(@_);
    }

    # All preconditions are validated.  Let's do some work.
    $self->{$attr} = $value
      if ( defined($value) );

    return $self->{$attr};
}

#------------------------------------------------------------
# $parameter parameter( $parameter )
#
# Currently the only formats supported are:
#  'YYYY/MM/DD' or 'YYYY-MM-DD' or
#  'MM/DD/YYYY' or 'MM-DD-YYYY
#
# Parameters:
#   $dateFormatString
#
# Return:
#   $scalar - private memeber value
#------------------------------------------------------------
sub parameter {
    my $self      = shift;
    my $parameter = shift;

    if ($parameter) {
        assert(
            $parameter && ( $parameter =~ /YYYY[-\/]MM[-\/]DD/
                || $parameter =~ /MM[-\/]DD[-\/]YYYY/ ), "Invalid date format"
        );

        $self->{_parameter} = $parameter;
    }

    return $self->{_parameter};
}

#------------------------------------------------------------
# $fail_status ok( $target_data )
#
# Check if target data string represents a valid date.
# Currently this only support strings in the format:
# MM/DD/YYYY.
#
# Parameters:
#   $target_data - Data we will be testing.
#
# Return:
#   $fail_status - kStatusOK (0) if the test passes, any
#                  non-zero should be considered a failure.
#------------------------------------------------------------
sub ok {
    my ( $self, $target, %args ) = @_;
    my $fail =
      defined( $self->{_fail_status} )
      ? $self->{_fail_status}
      : Validate::kStatusDefault;
    my $success = Validate::kStatusOK;

    return undef unless ( $self->is_configured() );

    # No test if the value is not defined.
    return $success unless ( defined($target) );

    my ( $month, $day, $year );

    # YYYY/MM/DD
    if ( $self->parameter =~ /YYYY[-\/]MM[-\/]DD/ ) {
        ( $year, $month, $day ) = split( /[-\/]/, $target );
    }

    # MM/DD/YYYY
    elsif ( $self->parameter =~ /MM[-\/]DD[-\/]YYYY/ ) {
        ( $month, $day, $year ) = split( /[-\/]/, $target );
    }

    #Unknown format
    else {
        die "Invalid date format";
    }

    # Ensure all variables are integers, otherwise we fail
    return $fail unless ( is_integer($month) && is_integer($day) && is_integer($year) );

    my $date = new Date::Simple("$year-$month-$day");

    return $date ? $success : $fail;
}

#------------------------------------------------------------
# Private Methods
#------------------------------------------------------------

#------------------------------------------------------------
# Validate::Rule _init()
# Initialize the object.
#
# - Build accessor method hash
# - set internal private data ( message, fail_status, and
#   parameter ). See the base class for parameter defintions.
#------------------------------------------------------------
sub _init {
    my ( $self, %args ) = @_;
    my @paramlist;

    # Build a hash with our valid class attributes
    foreach ( (kClassAttributes) ) {
        $self->{_attributes}->{$_}++;
    }

    $self->message( $args{message}                    ? $args{message}     : kFailureMessage );
    $self->fail_status( defined( $args{fail_status} ) ? $args{fail_status} : Validate::kStatusDefault );

    $self->parameter( $args{parameter} );

    $self->SUPER::_init(%args);

    return $self;
}

1;
