#!/usr/bin/perl -w

use strict;
use warnings;

use Carp qw(confess);
use File::Basename;
use Data::Dumper;

use XML::LibXML;
use XML::LibXSLT;

use Ernad::Erimp;

$|=1;

## use just any impna
my $impna=$ARGV[0] // '';
if(not $impna) {
  die "I don't have an impna parameter, try 'nep'.";
}

my $e=Ernad::Erimp->new({'impna'=>$impna});
my $style_dir=$e->{'dir'}->{'style'};
my $xslt_dir=$e->{'dir'}->{'xslt'};
my $source = XML::LibXML->load_xml(string => '<root/>');
my $xslt = XML::LibXSLT->new();

## holder for files in xslt/ that ar checked in style/
my $checked;
## must not be checked
#&check_dir($xslt_dir);
$checked=&check_dir($style_dir);

## not yet done, still a question mark over issue_text.
##&check_dir($xslt_dir,$checked);

sub check_dir {
  my $dir=shift;
  my $checked=shift;
  if(not -d $dir) {
    confess "I don't see your directory $dir";
  }
  my $find="find $dir -name '*.xslt.xml'";
  foreach my $file (`$find`) {
    chomp $file;
    if(not (-f $file or -l $file)) {
      next;
    }
    if(-f $file and $checked) {
      my $bana=basename($file);
      if($checked->{$bana}) {
        next;
      }
    }
    &check_file($file);
    if(not -l $file) {
      next;
    }
    my $link=basename(readlink($file));
    $checked->{$link}=1;
  }
  return $checked;
}

sub check_file {
  my $file=shift;
  if(not -f $file) {
    print "I don't have the file $file.";
    return;
  }
  if($file=~m|/sos/|) {
    return;
  }
  if($file=~m|/obsolete/|) {
    return;
  }
  if(not &check_output($file)) {
    print "$file produces no output.\n";
    return;
  }
  print "I test $file ... ";
  my $style_doc = XML::LibXML->load_xml(location=>$file, no_cdata=>1);
  my $stylesheet = $xslt->parse_stylesheet($style_doc);
  my $results = $stylesheet->transform($source);
  print "done\n";
}


sub check_output {
  my $in_file=shift;
  if(not -f $in_file) {
    die "I can't open $in_file";
  }
  my $doc = XML::LibXML->load_xml(location => $in_file);
  my $ns='http://www.w3.org/1999/XSL/Transform';
  my @output_els=$doc->getElementsByTagNameNS($ns,'output');
  return scalar @output_els;
}
