package Test::Library;

use strict;
use warnings;

use Type::Library
   -base,
   -declare => qw( ISODateTime AddressType2Code CountryCode );
use Type::Utils -all;
use Types::Standard -types;

our $VERSION = 0.02;

use DateTime;

declare ISODateTime =>
    as Str,
    where {
        ($_ =~ m{\A-?[0-9]{4,}-[0-9]{2}-[0-9]{2}T[0-2][0-9]:[0-5][0-9]:[0-5][0-9](?:Z|[-+]?[0-2][0-9]:[0-5][0-9])?\z}) && 
        (validate_datetime($_))
    };

declare AddressType2Code =>
    as enum ['ADDR','PBOX','HOME','BIZZ','MLTO','DLVY'];

declare CountryCode =>
    as Str,
    where {
        ($_ =~ m![A-Z]{2,2}!)
    };

sub validate_datetime {
    my ($date) = @_;

    $date =~ s/\A-//;
    my ($year,$month,$day,$hour,$min) = split /[-Z+:]/, $date;

    eval {
        DateTime->new(
            year  => $year,
            month => $month,
            day   => $day,
        );
    } or return 0;

    return 0 if ( $hour and ( $hour < 0 or $hour > 12 ) );
    return 0 if ( $min  and ( $min < 0 or $min > 59 ) );

    return 1;
}

1;
