#!/usr/bin/perl
use strict; use warnings;

use Data::Dumper; 
use OpenILS::Utils::Fieldmapper;  

my $map = $Fieldmapper::fieldmap;

print <<JS;

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

function FieldmapperException(message) {
	this.message = message;
}
FieldmapperException.toString = function() {
	return "FieldmapperException: " + this.message + "\\n";
}


JS

for my $object (keys %$map) {

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

print <<JS;

//  ----------------------------------------------------------------
// Class: $short_name
//  ----------------------------------------------------------------

JS

print	<<JS;

function $short_name(array) {

	this.classname = "$short_name";
	this._isfieldmapper = true;

	if(array) { 
		if( array.constructor == Array) 
			this.array = array;  

		else
			throw new FieldmapperException(
				"Attempt to build fieldmapper object with non-array");

	} else { this.array = []; }

}

$short_name._isfieldmapper = true;


JS

for my $field (keys %{$map->{$object}->{fields}}) {

my $position = $map->{$object}->{fields}->{$field}->{position};

print <<JS;
$short_name.prototype.$field = function(new_value) {
	if(new_value) { this.array[$position] = new_value; }
	return this.array[$position];
}
JS

}
}

