#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper; 
use OpenILS::Utils::Fieldmapper;  

my $map = $Fieldmapper::fieldmap;

# if a true value is provided, we generate the web (light) version of the fieldmapper
my $web = $ARGV[0];
# List of classes needed by the opac
my @web_hints = qw/ex mvr au aou aout asv asva asvr asvq 
		circ acp acpl acn ccs perm_ex ahn ahr aua ac 
		actscecm crcd crmf crrf mus mbts aoc aus/;

print <<JS;

//  ----------------------------------------------------------------
// Autogenerated by fieldmapper.pl
// Requires JSON.js
//  ----------------------------------------------------------------

function Fieldmapper() {}

var errorstr = "Attempt to build fieldmapper object with non-array";

Fieldmapper.prototype.clone = function() {
	var obj = new this.constructor();

	for( var i in this.a ) {
		var thing = this.a[i];
		if(thing == null) continue;

		if( thing._isfieldmapper ) {
			obj.a[i] = thing.clone();
		} else {

			if(instanceOf(thing, Array)) {
				obj.a[i] = new Array();

				for( var j in thing ) {

					if( thing[j]._isfieldmapper )
						obj.a[i][j] = thing[j].clone();
					else
						obj.a[i][j] = thing[j];
				}
			} else {
				obj.a[i] = thing;
			}
		}
	}
	return obj;
}
Fieldmapper.prototype.isnew = function(n) { if(arguments.length == 1) this.a[0] =n; return this.a[0]; }
Fieldmapper.prototype.ischanged = function(n) { if(arguments.length == 1) this.a[1] =n; return this.a[1]; }
Fieldmapper.prototype.isdeleted = function(a) { if(arguments.length == 1) this.a[0] =n; return this.a[0]; }
function FMEX(message) { this.message = message; }
FMEX.toString = function() { return "FieldmapperException: " + this.message + "\\n"; }

var _c = {};

JS

for my $object (keys %$map) {

	if($web) {
		my $hint = $map->{$object}->{hint};
		next unless (grep { $_ eq $hint } @web_hints );
	}

	my $short_name = $map->{$object}->{hint};

	my @fields;
	for my $field (keys %{$map->{$object}->{fields}}) {
		my $position = $map->{$object}->{fields}->{$field}->{position};
		$fields[$position] = $field;
	}

	print "_c[\"$short_name\"] = [";
	for my $f (@fields) { 
		if( $f ne "isnew" and $f ne "ischanged" and $f ne "isdeleted" ) {
			print "\"$f\","; 
		}
	}
	print "];\n"



}

print <<JS;

	var string = "";
	for( var cl in _c ) {
		string += cl + ".prototype = new Fieldmapper(); " + 
							cl + ".prototype.constructor = " + cl + ";" +
							cl + ".baseClass = Fieldmapper.constructor;" +
							"function " + cl + "(a) { " +
								"this.classname = \\\"" + cl + "\\\";" +
								"this._isfieldmapper = true;" +
								"if(a) { if(a.constructor == Array) this.a = a; else throw new FMEX(errorstr);} else this.a = []}"; 

		string += cl + "._isfieldmapper=true;";

		for( var pos in _c[cl] ) {
			var p = parseInt(pos) + 3;
			var field = _c[cl][pos];
			string += cl + ".prototype." + field + 
				"=function(n){if(arguments.length == 1)this.a[" + 
				p + "]=n;return this.a[" + p + "];};";
		}

	}

	eval(string);

JS

