#!/usr/bin/perl
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# this is the script to actually run the RDF Schema generator

use Carp;
use RDFStore::NodeFactory;
use RDFStore::Parser::SiRPAC;
use RDFStore::Vocabulary::Generator;
    
my $f = new RDFStore::NodeFactory();
my @schemas = ();

my ($outputDirectory, $packageClass, $namespace, $factoryStr);
      
# parse options
while (my $opt = shift @ARGV) {
	if($opt =~ /\-d/) {
		$outputDirectory = shift @ARGV;
	} elsif($opt =~ /\-o/) {
		$packageClass = shift @ARGV;
	} elsif($opt =~ /\-s/) {
		push @schemas,shift @ARGV;
	} elsif($opt =~ /\-n/) {
		$namespace = shift @ARGV;
	} elsif($opt =~ /\-f/) {
		$factoryStr = shift @ARGV;
	};
};

if(scalar(@schemas) == 0) {
	print STDERR "Usage: Generator {-s <schema file or URL>}+ -o <output class name> -n <namespace> [-f <node factory class name>] [-d <output directory>]\n"." If -d is not specified, generated class will be printed to standard output.\n";
	exit(1);
};

my $generator = new RDFStore::Vocabulary::Generator();
$packageClass = $generator->{DEFAULT_PACKAGE_CLASS}
	unless(defined $packageClass);

my $all;
foreach my $schemaURL (@schemas) {
	$namespace = $schemaURL
		unless(defined $namespace);

	my $p=new RDFStore::Parser::SiRPAC( ErrorContext => 2, 
				Style => 'RDFStore::Parser::Styles::RDFStore::Model',
				NodeFactory	=> $f,
				Source	=> $namespace );

	my $m = $p->parsefile($schemaURL);
	print STDERR "Reading schema from ".$schemaURL."\n";

        if(!(defined $all)) {
        	#$all = $m->find(); #tricky get a VirtualModel here :-) otherwise it would be a type-cast
        	$all = $m;
        } else {
        	$all->unite($m);
	};
#print $all->toStrawmanRDF(),"\n";
};

print STDERR "Total statements: ".$all->size(),"\n";

$outputDirectory .= '/'
        unless( (not(defined $outputDirectory)) || ($outputDirectory eq '') || ($outputDirectory =~ /\s+/) || ($outputDirectory =~ /\/$/) );

$generator->createVocabulary($packageClass, $all, $namespace, $outputDirectory, $factoryStr) or
	die "Could not generate vocabulary";
