#!/usr/bin/perl

use Template;
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 $tpl = Template->new({
		ABSOLUTE => 1
	});

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

	my $vars = {
		ns_prefix       => $prefix,
		output_basename => $basename,
		definition      => Xmldoom::ORB::Definition::generate($database, 'json')
	};

	$tpl->process(get_template('javascript'), $vars, $output)
		|| die $tpl->error(), "\n";
}

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;

