use strict;
use RIB::Util ();
use RIB::ConfigParser ();
use RIB::BIDMParser ();
$/ = undef;
select(STDOUT) ; $| = 1;

my $util = RIB::Util->new();
my $RIBDIR = $util->GetRibDir;
unless($RIBDIR){
    print "Could not get the name of the RIB directory\n";
    exit(0);
}
my $filepath = "$RIBDIR/repositories";
opendir(DIR,$filepath) or die "Couldn't open the directory $filepath: $!";
my $repo;
OUTER: foreach $repo ( readdir DIR ){
    next unless -d "$filepath/$repo";
    next if ($repo eq '.' or $repo eq '..');
    print "Repository $repo\n";
    my $cfile = "$filepath/$repo/conf/BIDM.conf";
    my $cp = RIB::ConfigParser->new();
    unless ($cp->load_config($cfile)){
	print "\tThere is a problem with $repo\'s configuration file.\n".
	      "\tProblem: " . $cp->ErrorMsg() . "!\n".
	      "\n\tContinuing to next repository!\n";
	next;
    }

    my $odir = "$filepath/$repo/objects";
    my $cdir = "$filepath/$repo/catalog";
    opendir(ODIR,$odir) or die "Couldn't open the directory $odir: $!";
    my $class;
    foreach $class ( readdir ODIR ){
	next if ($class eq '.' or $class eq '..');
	print "  Class $class\n";
	opendir(CDIR,"$odir/$class") 
	    or die "Couldn't open the directory $odir/$class: $!";
	my $file;
	foreach $file ( grep( /\.html?/i , readdir CDIR )){
	    my $oentry = "$odir/$class/$file";
	    my $centry = "$cdir/$class/$file";
	    print "    making new catalog entry for $file\n";
	    my $bp = RIB::BIDMParser->new();
	    unless($bp->parse_file($oentry)){
		print "\tThere was a problem loading $file.\n".
		      "\tReason: " . $bp->ErrorMsg . "\n".
		      "\n\tContinuing...\n";
		next;
	    }
	    my $ob = $cp->InstanceOf('',$class,$bp);
	    my $buf;
	    if(!$ob->AsHtml(\$buf,$repo,$file,$cp)){
		print "\tThere were problems creating catalog entry $file.\n". 
		      "\tReason : ". $ob->ErrorMsg . ".\n".
		      "\n\tContinuing...\n";
		next;
	    } else {
		unless (open (PAGE,">$centry")) {
		    print "\tCouldn't write to $centry.\n".
			  "\tReason: $!\n".
			  "\n\tContinuing...\n";
		    next;
		}
		print PAGE $util->ClassHeader($class,$repo);
		print PAGE $buf;
		print PAGE $util->ClassFooter($class,$repo);
		close(PAGE);
	    }
	    $buf = '';
	}
    }
}
