#
# test the pbib script
#
use strict;
use Test::More;
use File::Compare;
use File::Spec;
use FindBin;

BEGIN {
	my @features = eval("use PBib::PBib::ConfigData; PBib::PBib::ConfigData->feature_names();");
	if( @features ) {
		plan( tests => 3 + 5 * 4 ); # no. file types * 4
	} else {
		plan(skip_all => "This test need the ConfigData generated by Module::Build. This should be available in blib, e.g. use perl -Mblib=blib or if PBib is installed correctly");
		}
	use_ok( 'PBib::PBib::ConfigData' );
}

# find pbib.pl
my $pbib = File::Spec->catfile($FindBin::Bin, '..', 'bin', 'pbib.pl');
ok( -r $pbib, "'$pbib' exists");
my $perl = $^X;
ok( -x $perl, "'$perl' is executable");

# system("pbib ....");
# for all document types, but only for a single bib data source

# to be able to test which features are enabled in this installation
my %types = qw(
	rtf MSWord
	sxw OpenOffice
	txt 0
	html 0
	xml XML
	);
	# doc MSWord #### this simple file compare does not work for MS Word generated files
my $dir = 't';

# setup test configuration for pbib
$ENV{PBIB_CONFIG} = join(',', qw(
	argv=0
	env=0
	site=0
	user=0
	default=1
	verbose=0
	quiet=1
	biblio.file=t/sample.bib));

foreach my $ext (sort keys %types) {
	SKIP: {
		# is this file format enabled?
		if( $types{$ext} ) {
			skip("Support for $types{$ext} documents is not enabled", 4)
				unless( PBib::PBib::ConfigData->feature("doc_$types{$ext}") );
		}
		
		
		my $file = File::Spec->catfile($dir, "sample.$ext");
		my $output = File::Spec->catfile($dir, "sample-pbib.$ext");
		my $expected = File::Spec->catfile($dir, "expected-sample-pbib.$ext");
		
		diag("Converting $file ...");
		unlink($output) if -e $output; # delete output file first
		unlink("$output.log") if -e "$output.log";
		ok( -r $file, "$file is readable");
		ok( -r $expected, "$expected is readable");
		unless( -r $file && -r $expected ) {
			skip("Test files missing, maybe the distribution is corrupt.", 2);
		}
		my $result = system($perl, $pbib, $file);
		is($result, 0, "system($perl, $pbib, $file)");
		skip("running pbib failed", 1) if $result;
		# compare result with expected result
		ok(File::Compare::compare($output, $expected) == 0, "PBib::convertFile($file) produces expected output file");
	}
}

# also test pbib-export, pbib-import (as separate tests!)