# ESIS-GH3900 by Benedikt Wolf (D-ECHO) based on A320 canvas avionics by Joshua Davidson

var ESIS_GH3900_main = nil;
var ESIS_GH3900_start = nil;
var ESIS_GH3900_display = nil;

var base = props.globals.initNode("/instrumentation/esis-gh3900");

var volts		=	props.globals.getNode("/systems/electrical/outputs/stby-batt", 1);

var instrument_path	=	"Aircraft/do228/Models/Instruments/ESIS-GH3900/";

# Instrument Properties
var ias_kts		=	props.globals.getNode("instrumentation/airspeed-indicator/indicated-speed-kt", 1);
var ias_mach		=	props.globals.getNode("instrumentation/airspeed-indicator/indicated-mach", 1);
var no_wow		=	props.globals.getNode("fdm/jsbsim/fcs/gear-no-wow");
var gs			=	props.globals.getNode("velocities/groundspeed-kt");
var sat			=	props.globals.getNode("environment/temperature-degc");
var pitch		=	props.globals.getNode("orientation/pitch-deg");
var roll		=	props.globals.getNode("orientation/roll-deg");
var turn		=	props.globals.getNode("instrumentation/turn-indicator/indicated-turn-rate");
var radaralt		=	props.globals.getNode("instrumentation/radar-altimeter/radar-altitude-ft");
var heading		=	props.globals.getNode("orientation/heading-deg");
var wind_from		=	props.globals.getNode("environment/wind-from-heading-deg");
var wind_spd		=	props.globals.getNode("environment/wind-speed-kt");
var vs_fpm		=	props.globals.getNode("instrumentation/vertical-speed-indicator/indicated-speed-fpm");
var alt			=	props.globals.getNode("instrumentation/altimeter/indicated-altitude-ft");
var qnh			=	props.globals.getNode("instrumentation/altimeter/setting-hpa");
var slip_skid_ball	=	props.globals.getNode("instrumentation/slip-skid-ball/indicated-slip-skid");

var state = 0;	# 0 = off; 1 = starting; 2 = running


var roundToNearest = func(n, m) {
	var x = int(n/m)*m;
	if((math.mod(n,m)) > (m/2) and n > 0)
			x = x + m;
	if((m - (math.mod(n,m))) > (m/2) and n < 0)
			x = x - m;
	return x;
}

var canvas_ESIS_GH3900_base = {
	init: func(canvas_group, file) {
		var font_mapper = func(family, weight) {
			return "LiberationFonts/LiberationSans-Bold.ttf";
		};

		
		canvas.parsesvg(canvas_group, file, {'font-mapper': font_mapper});

		var svg_keys = me.getKeys();
		 
		foreach(var key; svg_keys) {
			me[key] = canvas_group.getElementById(key);
			var clip_el = canvas_group.getElementById(key ~ "_clip");
			if (clip_el != nil) {
				clip_el.setVisible(0);
				var tran_rect = clip_el.getTransformedBounds();
				var clip_rect = sprintf("rect(%d,%d, %d,%d)", 
				tran_rect[1], # 0 ys
				tran_rect[2], # 1 xe
				tran_rect[3], # 2 ye
				tran_rect[0]); #3 xs
				#   coordinates are top,right,bottom,left (ys, xe, ye, xs) ref: l621 of simgear/canvas/CanvasElement.cxx
				me[key].set("clip", clip_rect);
				me[key].set("clip-frame", canvas.Element.PARENT);
			}
		}

		if( me["horizon.fg"] != nil and me["horizon.bg"] != nil  ){
			me.h_trans_f = me["horizon.fg"].createTransform();
			me.h_rot_f = me["horizon.fg"].createTransform();
			me.h_trans_b = me["horizon.bg"].createTransform();
			me.h_rot_b = me["horizon.bg"].createTransform();
		}
		
		me.page = canvas_group;

		return me;
	},
	getKeys: func() {
		return [];
	},
	update: func() {
		if( state == 2 ){
			ESIS_GH3900_start.page.hide();
			ESIS_GH3900_main.page.show();
			ESIS_GH3900_main.update();
		} else if ( state == 1 ){
			ESIS_GH3900_main.page.hide();
			ESIS_GH3900_start.page.show();
		} else {
			ESIS_GH3900_main.page.hide();
			ESIS_GH3900_start.page.hide();
		}
	},
};

var canvas_ESIS_GH3900_main = {
	new: func(canvas_group, file) {
		var m = { parents: [canvas_ESIS_GH3900_main , canvas_ESIS_GH3900_base] };
		m.init(canvas_group, file);

		return m;
	},
	getKeys: func() {
		return ["asi.digits.10", "asi.rollingdigits", "asi.tape", "asi.tape.lowspeed", "mach.digits", "gs", "horizon.fg", "horizon.bg", "roll.needle", "slip_skid_ball",
		"compass", 
		"heading.digits", "hdg_sel",
		"vs.digits","vs.arrow",
		"alt.tape", "alt.1", "alt.2", "alt.3", "alt.4", "alt.5", "alt.6", "alt.7",
		"alt.digits.100", "alt.rollingdigits",
		"metric_alt.digits",
		"qnh.digits", "qnh.unit"
		];
	},
	update: func() {
		# Airspeed Indicator
		var airspeed = ias_kts.getDoubleValue();
		if( airspeed > 10 ) {
			me["asi.digits.10"].setText( sprintf("%2d", math.floor( airspeed / 10 , 1) ) );
			me["asi.digits.10"].show();
		} else {
			me["asi.digits.10"].hide();
		}
		me["asi.rollingdigits"].setTranslation( 0, math.mod( airspeed, 10 ) * (-4.0) );
		me["asi.tape"].setTranslation( 0, 4.625 * airspeed );
		#if( no_wow.getValue() == 1 ) {
		#	me["asi.tape.lowspeed"].show();
		#} else {
		#	me["asi.tape.lowspeed"].hide();
		#}
		# Mach Indicator
		me["mach.digits"].setText(sprintf("%03d", math.round( 1000 * ias_mach.getDoubleValue() ) ) );
		
		# Groundspeed
		me["gs"].setText( sprintf("%3d", math.round( gs.getDoubleValue() ) ) );
		
		# Attitude Indicator
		var roll_v = roll.getDoubleValue();
		me.h_trans_f.setTranslation( 0, pitch.getDoubleValue() * 7.2 );
		me.h_rot_f.setRotation( -roll_v * D2R , me["horizon.fg"].getCenter() );
		me.h_trans_b.setTranslation( 0, pitch.getDoubleValue() * 7.2 );
		me.h_rot_b.setRotation( -roll_v * D2R , me["horizon.bg"].getCenter() );
		me["roll.needle"].setRotation( -roll_v * D2R );
		
		# Slip/Skid Ball
		me["slip_skid_ball"].setTranslation( math.clamp( slip_skid_ball.getDoubleValue(), -1, 1 ) * 26, 0 );
		
		# HSI
		var heading_v = heading.getDoubleValue(); #4.34
		me["compass"].setTranslation( -heading_v * 4.34, 0 );
		me["heading.digits"].setText( sprintf("%3d", math.round( heading_v ) ) );
		
		# Vertical Speed Indicator
		var vs = vs_fpm.getDoubleValue();
		me["vs.digits"].setText( sprintf("%4d", math.round( math.abs( vs ) ) ) );
		if( vs < 0 ){
			me["vs.arrow"].show();
			me["vs.arrow"].setRotation( 0 );
		} else if ( vs > 0 ){
			me["vs.arrow"].show();
			me["vs.arrow"].setRotation( 180 * D2R );
		} else {
			me["vs.arrow"].hide();
		}
		
		# Altimeter
		# spacing: 0.343 per ft
		
		#Alt Tape
		var altitude = alt.getDoubleValue();
	#	me["alt.tape"].setTranslation(0,(altitude - roundToNearest(altitude, 1000))*0.343);
		var alt_num_small = [ "000", "000", "000" ];
		var alt_num_big = [ 0, 0, 0 ];
		if (roundToNearest(altitude, 1000) == 0) {
			alt_num_small = [ "-500", "000", "500" ];
			alt_num_big = [ 0, 0, 0 ];
		} elsif (roundToNearest(altitude, 1000) > 0) {
			var tmp = roundToNearest(altitude, 500) / 100;
			alt_num = [ tmp-15, tmp-10, tmp-5, tmp, tmp+5, tmp+10, tmp+15 ];
		} elsif (roundToNearest(altitude, 1000) < 0) {
			var altNumLow = roundToNearest(altitude, 1000)/100+5;
			var altNumHigh = (roundToNearest(altitude, 1000)/1000 + 1)*10+5 ;
			var altNumCenter = altNumLow-5;
		}
	#	me["alt.small.1"].setText( sprintf( "%s", alt_num_small[0] ) );
	#	me["alt.small.2"].setText( sprintf( "%s", alt_num_small[1] ) );
	#	me["alt.small.3"].setText( sprintf( "%s", alt_num_small[2] ) );
	#	
	#	me["alt.big.1"].setText( sprintf( "%s", alt_num_big[0] ) );
	#	me["alt.big.2"].setText( sprintf( "%s", alt_num_big[1] ) );
	#	me["alt.big.3"].setText( sprintf( "%s", alt_num_big[2] ) );
		
		me["alt.digits.100"].setText( sprintf("%3d", math.floor( altitude / 100 ) ) );
		me["alt.rollingdigits"].setTranslation( 0, math.mod( altitude, 100 ) * 1.5 );
		
		me["metric_alt.digits"].setText( sprintf("%5d", math.round( altitude * FT2M ) ) );
		
		me["qnh.digits"].setText( sprintf("%4d", qnh.getDoubleValue() ) );
		me["qnh.unit"].setText("hPa");
	}
};


var canvas_ESIS_GH3900_start = {
	new: func(canvas_group, file) {
		var m = { parents: [canvas_ESIS_GH3900_start , canvas_ESIS_GH3900_base] };
		m.init(canvas_group, file);

		return m;
	},
	getKeys: func() {
		return [];
	},
	update: func() {
	}
	
};



var efi_pfd_update = maketimer(0.1, func {
	canvas_ESIS_GH3900_base.update();
});
efi_pfd_update.simulatedTime = 1;

var ls_pfd = setlistener("sim/signals/fdm-initialized", func {
	ESIS_GH3900_display = canvas.new({
		"name": "ESIS_GH3900",
		"size": [512, 512],
		"view": [512, 512],
		"mipmapping": 1
	});
	ESIS_GH3900_display.addPlacement({"node": "esis-gh3900.display"});
	
	var groupMain = ESIS_GH3900_display.createGroup();
	var groupStart = ESIS_GH3900_display.createGroup();


	ESIS_GH3900_main = canvas_ESIS_GH3900_main.new(groupMain, instrument_path~"esis-gh3900.svg");
	ESIS_GH3900_start = canvas_ESIS_GH3900_start.new(groupStart, instrument_path~"esis-gh3900-start.svg");

	efi_pfd_update.start();
	
	removelistener(ls_pfd);
});

var check_state = func () {
	if ( state == 0 ){
		if ( volts.getValue() >= 10 ) {
			state = 1;
			settimer( func() { state = 2 } , 4 );
		}
	} else {
		if ( volts.getValue() < 10 ){
			state = 0;
		}
	}
}

setlistener(volts, func{
	check_state();
});
