package AMF::Spec::Check;

use strict;
use Carp::Assert;

sub process_value {
  my $spec     = shift;
  my $typename = shift;
  my $value    = shift;

  assert( $typename );
  
  my $type = $spec -> {types} {$typename};

  if ( not $type ) {
#    warn "can't check against an undefined type: $typename";
#    warn "type $typename is not defined\n";
    return $value;
  }
  

  my $result;

  my $typetype = $type -> [0];
  my $typedef  = $type -> [1][0];
  
  assert( $typetype );
  assert( $typetype eq 'text' );
  assert( $typedef );
  assert( ref $typedef );
  assert( ref $typedef eq 'ARRAY' );

  my $checktype = $typedef -> [0];
  my $checkspec = $typedef;

  if ( $checktype ) { 
    assert( $checktype );
    assert( $checkspec );
    
    my $func = "check_against_$checktype";

    if ( $checktype eq 'function' ) {
      $func = $checkspec -> [1];
    }
    
    { no strict 'refs'; 
      $result = &$func( $value, $checkspec );
    }
    
  } else {
    warn "didn't find typedef for $typename";
    $result = $value;
  }

  return $result;
}


sub check_against_re {
  my $val = shift;
  my $def = shift;
  my $exp = $def ->[1];

  assert( defined $val );
  assert( $exp );

#  print "CHECK: $val AGAINST: $exp\n";

  if ( $val =~ m/$exp/ ) {
    return $1;

  } else {
    return undef;
  }
}


sub check_against_variants {
  my $val = shift;
  my $variants = shift;

#  print "CHECK: $val AGAINST VAR: @$variants\n";
  
  foreach ( @$variants ) {
    if ( $val eq $_ ) {
#      print "OK\n";
      return $val;
    }
  } 
  return undef;
}




1;

