#!/usr/bin/perl

#use File::ShareDir;
#use File::Spec;
use File::Basename;
use IO::File;
use Xmldoom::Definition;
use Xmldoom::ORB::Definition;
use Getopt::Std qw( getopts );
use strict;

# for debugging
use Data::Dumper;
use Carp;

$SIG{__DIE__} = sub {
	Carp::confess(@_);
	#Carp::confess;
};

#sub get_template
#{
#	my $tpl_name = shift;
#
#	# TODO: find a better way to do this!
#	if ( -e "share/tpl/$tpl_name.tpl" )
#	{
#		return File::Spec->rel2abs("share/tpl/$tpl_name.tpl");
#	}
#
#	return File::ShareDir::dist_file('Xmldoom', "tpl/$tpl_name.tpl");
#}

sub generate_javascript
{
	my $database = shift;
	my $prefix   = shift;
	my $output   = shift;

	my $json_def = Xmldoom::ORB::Definition::generate($database, 'json');

	my ($basename, $tmp, $tmp) = fileparse( $output, qr/\.[^.]*/ );

	my $header_text = << "EOF";
//
// This file was automatically generated by xmldoom-generate 0.0.13 !
//

dojo.provide('$prefix.$basename');

//
// A JSON dump of the object definitions.
//

EOF

	my $fd = IO::File->new($output, 'w');
	$fd->write($header_text);
	$fd->write("$prefix.$basename = '$json_def';\n\n");
	$fd->close();
}

sub main
{
	my %conf;

	getopts('l:D:X:N:o:', \%conf);

	if ( not defined $conf{l} )
	{
		die "Must pass a language -l to generate";
	}
	if ( $conf{l} ne 'javascript' )
	{
		die "Currently only -l javascript is supported";
	}
	if ( not defined $conf{D} or not defined $conf{X} )
	{
		die "Must set both -D database.xml and -X objects.xml for the desired database";
	}
	if ( not defined $conf{N} )
	{
		die "Must define a namespace prefix with -N Namespace.Prefix";
	}

	my $language     = $conf{l};
	my $database_xml = $conf{D};
	my $objects_xml  = $conf{X};
	my $prefix       = $conf{N};
	my $output       = $conf{o};

	# load the Xmldoom data
	my $database = Xmldoom::Definition::parse_database_uri($database_xml);
	Xmldoom::Definition::parse_object_uri($database, $objects_xml);

	if ( $language eq 'javascript' )
	{
		generate_javascript($database, $prefix, $output);
	}
	else
	{
		die "Unsupported language type: " . $language;
	}
}

main;

