package WebPAC::Validate;

use warnings;
use strict;

use blib;

use base 'WebPAC::Common';
use File::Slurp;
use List::Util qw/first/;
use Data::Dumper;
use WebPAC::Normalize qw/_pack_subfields_hash/;
use Storable qw/dclone/;

=head1 NAME

WebPAC::Validate - provide simple validation for records

=head1 VERSION

Version 0.04

=cut

our $VERSION = '0.04';

=head1 SYNOPSIS

This module provide a simple way to validate your file against a simple
configuration file in following format:

  # field 10 doesn't have any subfields
  10
  # same with 101
  101
  # field 200 have valid subfields a-g
  # and field e is repeatable
  200 a b c d e* f g
  # field 205 can have only subfield a
  # and must exists
  205! a
  # while 210 can have a c or d
  210 a c d

=head1 FUNCTIONS

=head2 new

Create new validation object

  my $validate = new WebPAC::Validate(
  	path => 'conf/validate/file',
  );

=cut

sub new {
	my $class = shift;
	my $self = {@_};
	bless($self, $class);

	my $log = $self->_get_logger();

	foreach my $p (qw/path/) {
		$log->logconfess("need $p") unless ($self->{$p});
	}

	my $v_file = read_file( $self->{path} ) ||
		$log->logdie("can't open validate path $self->{path}: $!");

	my $v;
	my $curr_line = 1;

	foreach my $l (split(/[\n\r]+/, $v_file)) {
		$curr_line++;

		# skip comments and whitespaces
		next if ($l =~ /^#/ || $l =~ /^\s*$/);

		$l =~ s/^\s+//;
		$l =~ s/\s+$//;

		my @d = split(/\s+/, $l);

		my $fld = shift @d;

		if ($fld =~ s/!$//) {
			$self->{must_exist}->{$fld}++;
		}

		$log->logdie("need field name in line $curr_line: $l") unless (defined($fld));

		if (@d) {
			$v->{$fld} = [ map {
				my $sf = $_;
				if ( $sf =~ s/!(\*)?$/$1/ ) {
					$self->{must_exist_sf}->{ $fld }->{ $sf }++;
				};
				$sf;
			} @d ];
		} else {
			$v->{$fld} = 1;
		}

	}

	$log->debug("current validation rules: ", Dumper($v));

	$self->{rules} = $v;

	$log->info("validation uses rules from $self->{path}");

	$self ? return $self : return undef;
}

=head2 validate_errors

Validate record and return errors

  my @errors = $validate->validate_errors( $rec );

=cut

sub validate_errors {
	my $self = shift;

	my $log = $self->_get_logger();

	my $rec = shift || $log->logdie("validate_errors need record");

	$log->logdie("rec isn't HASH") unless (ref($rec) eq 'HASH');
	$log->logdie("can't find validation rules") unless (my $r = $self->{rules});

	my @errors;

	$log->debug("rec = ", sub { Dumper($rec) }, "keys = ", keys %{ $rec });

	my $fields;

	foreach my $f (keys %{ $rec }) {

		next if (!defined($f) || $f eq '' || $f eq '000');

		$fields->{$f}++;

		if ( ! defined($r->{$f}) ) {
			push @errors, "field '$f' shouldn't exists";
			next;
		}


		if (ref($rec->{$f}) ne 'ARRAY') {
			push @errors, "field '$f' isn't repetable, probably bug in parsing input data";
			next;
		}

		foreach my $v (@{ $rec->{$f} }) {
			# can we have subfields?
			if (ref($r->{$f}) eq 'ARRAY') {
				# are values hashes? (has subfields)
				if (ref($v) ne 'HASH') {
					push @errors, "$f has value without subfields: $v";
					next;
				} else {

					my $h = dclone( $v );

					my $sf_repeatable;

					delete($v->{subfields}) if (defined($v->{subfields}));

					my $subfields;

					foreach my $sf (keys %{ $v }) {

						$subfields->{ $sf }++;

						# is non-repeatable but with multiple values?
						if ( ! first { $_ eq $sf.'*' } @{$r->{$f}} ) {
							if ( ref($v->{$sf}) eq 'ARRAY' ) {
								$sf_repeatable->{$sf}++;
							};
							if (! first { $_ eq $sf } @{ $r->{$f} }) {
								push @errors, "$f has unknown subfield: $sf";
							}
						}

					}
					if (my @r_sf = sort keys( %$sf_repeatable )) {
						my $plural = $#r_sf > 0 ? 1 : 0;

						push @errors, "$f subfield" .
						( $plural ? 's ' : ' ' ) .
						join(', ', @r_sf) .
						( $plural ? ' are ' : ' is ' ) .
						'repeatable in: ' .
						join('', _pack_subfields_hash( $h, 1) );
					}

					if ( defined( $self->{must_exist_sf}->{$f} ) ) {
						foreach my $sf (sort keys %{ $self->{must_exist_sf}->{$f} }) {
warn "====> $f $sf must exist\n";
							push @errors, "$f missing required subfield $sf"
								unless (
									defined( $subfields->{$f} ) &&
									defined( $subfields->{$f}->{$sf} )
								)
						}
					}

				}
			} elsif (ref($v) eq 'HASH') {
				push @errors, "$f has subfields which is not valid";
			}
		}
	}

	foreach my $must (sort keys %{ $self->{must_exist} }) {
		next if ($fields->{$must});
		push @errors,
			"field $must should exist, but it doesn't";
	}

	#$log->logcluck("return from this function is ARRAY") unless wantarray;

	$log->debug("errors: ", join(", ", @errors)) if (@errors);

	return @errors;
}

=head1 AUTHOR

Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>

=head1 COPYRIGHT & LICENSE

Copyright 2006 Dobrica Pavlinusic, All Rights Reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

=cut

1; # End of WebPAC::Validate
