#
#===============================================================================
#
#  DESCRIPTION: 
#
#===============================================================================

package TestUtils;
use Modern::Perl;
use utf8;
 
sub load_data{
    my ($config, $tables_used_in_test) = @_;
    my $home_dir = $config->{path_to_app_root};

    require "$home_dir/setup/lims.sql";
    require "$home_dir/t/test_data_extra.pl";
    # needs to be loaded *after* ROSEDB_DEVINIT env var set:
    require LIMS::DB;

    my $db = LIMS::DB->new_or_cached;

    my $dbh  = $db->retain_dbh or die LIMS::DB->error;
    my $dsn  = $db->dsn; # warn Dumper $dsn;
    my $dbix = DBIx::Simple->new($dbh);

    use vars qw($SQL_FOR_TABLE $FOREIGN_KEYS $TEST_DATA ); # from test_data.pl

	# make sure test_db exists:
	$dbh->do( 'CREATE DATABASE IF NOT EXISTS `lims_test`' ); # too late - already fails during connect

	# switch fk check off:
	$dbh->do( 'SET foreign_key_checks = 0' );

    foreach my $tbl ( keys %$SQL_FOR_TABLE ) { # print $tbl, "\n";
        next unless grep { $tbl =~ /^$_$/ } @$tables_used_in_test;
        my $sql = $SQL_FOR_TABLE->{$tbl}; # warn $sql;
		next if $sql =~ /DEFINER/; # not needed (or fatal) for tests

        local $dbh->{'RaiseError'} = 1;
        local $dbh->{'PrintError'} = 0;

		$dbh->do( qq!DROP TABLE IF EXISTS `$tbl`! );
		$dbh->do( $sql );
    }
	# switch fk check back on:
	$dbh->do( 'SET foreign_key_checks = 1' );

    foreach my $t( keys %$TEST_DATA ) { # warn $t, "\n";
        next unless grep { $t =~ /^$_$/ } @$tables_used_in_test;
        my $table  = $t,
        my $fields = $TEST_DATA->{$t}->{fields};
        my $values = $TEST_DATA->{$t}->{values};

        foreach my $data_set (@$values) { # warn $set, "\n";
            my $i = 0;
            # map field_name to its value:
            my %data = map { $fields->[$i++] => $_ } @$data_set; # warn Dumper \%data;

            $dbix->insert($t, \%data);
        }
    }
return $dbix;
}

1;
