#!/usr/bin/perl

use strict;
use warnings;

#use Test::More tests => 13;
use Test::More qw(no_plan);
use Rose::DB;
use Rose::DB::Object::Metadata::Column::Date;
use Rose::DB::Object::Metadata::Column::Time;
use Rose::DB::Object::Metadata::Column::Varchar;
use Rose::DB::Object::Metadata::Column::Integer;

# all calls to parse_value need a Rose::DB object
my $db = Rose::DB->new(driver => 'sqlite');

my $date_column = Rose::DB::Object::Metadata::Column::Date->new;
my $time_column = Rose::DB::Object::Metadata::Column::Time->new;
my $varchar_column = Rose::DB::Object::Metadata::Column::Varchar->new( 'length' => 10, overflow => 'fatal' );
my $integer_column = Rose::DB::Object::Metadata::Column::Integer->new;


# Test dates
ok(is_valid_db_column_value($date_column, $db, '2000-02-29'), "2000-02-29 is a valid Date");
ok(is_valid_db_column_value($date_column, $db, '2001-02-28'), "2001-02-28 is a valid Date");
ok(! is_valid_db_column_value($date_column, $db, '2001-01-31b'), "2001-02-29 is NOT a valid Date");
ok(! is_valid_db_column_value($date_column, $db, '2001-02-29'), "2001-02-29 is NOT a valid Date");

# Test times
ok(is_valid_db_column_value($time_column, $db, '10:00'), "10:00 is a valid Time");
ok(is_valid_db_column_value($time_column, $db, '10:00pm'), "10:00pm is a valid Time");
ok(! is_valid_db_column_value($time_column, $db, '10:00gm'), "10:00gm is a NOT valid Time");
ok(! is_valid_db_column_value($time_column, $db, '10:60'), "10:60 is a NOT valid Time");

# Test varchars
ok(is_valid_db_column_value($varchar_column, $db, '1234567890'), "1234567890 is a valid Varchar(10)");
ok(is_valid_db_column_value($varchar_column, $db, ''), "'' Is a valid Varchar(10)");
ok(! is_valid_db_column_value($varchar_column, $db, '12345678901'), "12345678901 is a NOT valid Varchar(10) (this test currently fails)");

# Test integers
ok(is_valid_db_column_value($integer_column, $db, '123'), "123 is a valid Varchar(10)");
ok(! is_valid_db_column_value($integer_column, $db, 'abc'), "abc Is a NOT valid Integer (this test currently fails)");

sub is_valid_db_column_value {
    my $column = shift;
    my $db     = shift;
    my $value  = shift;

    # Reset any errors in the Rose::DB object
    $db->error(undef);

    my $parsed = $column->parse_value($db, $value);

    # Sometimes 'parse_error' is set if the parsing failed
    # sometimes 'error' will be set on the Rose::DB object if parsing failed
    return ($column->parse_error || $db->error || !defined($parsed)) ? 0 : 1;
}

