package TestUtils;

use strict;
use warnings;

use Grep::Query qw(qgrep);

use Test::More;
use Test::Differences;

use TestInfo;

sub runAsNonFieldedTests
{
	my $name = shift;
	
	my @data = @{TestInfo::getData($name)};
	my @tests = @{TestInfo::getTests($name)};
	
	plan tests => scalar(@tests) * 3;
	
	my $group = 1;
	foreach my $t (@tests)
	{
		note("== GROUP $name/$group ==");
		
		my $q = $t->{q};
	
		my $desc = $q . ($t->{desc} ? " ($t->{desc})" : ''); 
	
		my @matchesNonOO = qgrep($q, @data);
		eq_or_diff(\@matchesNonOO, $t->{e}, "(NON-OO) $desc");
		
		my $gq = Grep::Query->new($q);
		my @matchesOO = $gq->qgrep(@data);
		eq_or_diff(\@matchesOO, $t->{e}, "(OO) $desc");
		
		if ($q =~ s/regexp/=~/ig)
		{
			$desc = $q . ($t->{desc} ? " ($t->{desc})" : ''); 
			my @matchesNonOOTildeOp = qgrep($q, @data);
			eq_or_diff(\@matchesNonOOTildeOp, $t->{e}, "(EQTILDE, NON-OO) $desc");
		}
		else
		{
			pass("(no regexp op involved)");
		}
		
		$group++;
	}
}

sub runAsFieldedTests
{
	my $name = shift;
	
	my %data = %{TestInfo::getData($name)};
	my @dataValues;
	push(@dataValues, $data{$_}) foreach (sort(keys(%data)));
	my @tests = @{TestInfo::getTests($name)};
	my @fieldAccessors = @{TestInfo::getFieldAccessors($name)};
	my $matchAdjustor = TestInfo::getMatchAdjustor($name);
	
	plan tests => scalar(@tests) * ( 3 * scalar(@fieldAccessors) );
	
	my $group = 1;
	foreach my $t (@tests)
	{
		note("== GROUP $name/$group ==");

		foreach my $fa (@fieldAccessors)
		{
			my $q = $t->{q};

			my $faDesc = defined($fa) ? 'explicit' : 'autogenerated';
			my $desc = $q . ($t->{desc} ? " $faDesc field accessor ($t->{desc})" : ''); 

			my @matchesNonOO = qgrep($q, $fa, @dataValues);
			my $adjustedMatchesNonOO = $matchAdjustor->(\@matchesNonOO);
			eq_or_diff($adjustedMatchesNonOO, $t->{e}, "(NON-OO) $desc");

			my $gq = Grep::Query->new($q);
			my @matchesOO = $gq->qgrep($fa, @dataValues);
			my $adjustedMatchesOO = $matchAdjustor->(\@matchesOO);
			eq_or_diff($adjustedMatchesOO, $t->{e}, "(OO) $desc");

			if ($q =~ s/regexp/=~/ig)
			{
				$desc = $q . ($t->{desc} ? " ($t->{desc})" : ''); 
				my @matchesNonOOTildeOp = qgrep($q, $fa, @dataValues);
				my $adjustedMatchesNonOOTildeOp = $matchAdjustor->(\@matchesNonOOTildeOp);
				eq_or_diff($adjustedMatchesNonOOTildeOp, $t->{e}, "(EQTILDE, NON-OO) $desc");
			}
			else
			{
				pass("(no regexp op involved)");
			}
		}
				
		$group++;
	}
}

1;