# AIR Avionics/Garrecht TRX-2000 by Bea Wolf (D-ECHO) based on

# A3XX Lower ECAM Canvas
# Joshua Davidson (it0uchpods)

#	Reference: https://www.air-avionics.com/support/TRX_2000_USR_rev1.0e.pdf
#######################################

var TRX2000_start = nil;
var TRX2000_radar = nil;
var TRX2000_standby = nil;
var TRX2000_display = nil;

var time = {
	hour:		props.globals.getNode("/sim/time/utc/hour",   1),
	minute:	props.globals.getNode("/sim/time/utc/minute", 1),
	second:	props.globals.getNode("/sim/time/utc/second", 1),
};

var flarm_receive = props.globals.getNode("/instrumentation/FLARM/receive-internal", 1);

var pushknob = props.globals.initNode( "/instrumentation/TRX2000/on-btn", 0, "BOOL" );

var TRX = props.globals.getNode("/instrumentation/TRX2000");
var range    = TRX.initNode("range-km", 6.0, "DOUBLE");
var selected = TRX.initNode("selected", -1, "INT");
var nearest  = TRX.initNode("nearest", -1, "INT");

var status = -1;	# 0 = off, 1 = start, 2 = on
var volts = props.globals.getNode("/systems/electrical/outputs/tcas", 1);

var serviceable = 1;
setlistener( "/instrumentation/TRX2000/serviceable", func( i ){
	serviceable = i.getBoolValue();
});

var instrument_dir = "Aircraft/DR400-Ecoflyer/Models/Interior/Panel/Instruments/TRX-2000/";

var all_contacts = props.globals.getNode("/instrumentation/FLARM/contacts");

var last_nearest = -1;

setlistener("/instrumentation/TRX2000/nearest", func(i){
	var n = i.getValue();
	if(n != last_nearest){
		#print (n~" is not equal to "~last_nearest);
		selected.setValue(n);
		last_nearest=n;
	}
});		


var canvas_TRX2000_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);
			}
		}

		me.page = canvas_group;

		return me;
	},
	getKeys: func() {
		return [];
	},
	update: func() {
		if( serviceable ){
			var volt = volts.getDoubleValue();
			if ( status == 2 and volt > 9) {
				if( flarm_receive.getBoolValue() ){
					TRX2000_radar.page.show();
					TRX2000_radar.update();
					TRX2000_standby.page.hide();
				}else{
					TRX2000_standby.page.show();
					TRX2000_standby.update();
					TRX2000_radar.page.hide();
				}
				TRX2000_start.page.hide();			
			} else if ( status == 1 and volt > 9 ){
				TRX2000_standby.page.hide();
				TRX2000_start.page.show();
				TRX2000_radar.page.hide();
			} else {
				TRX2000_standby.page.hide();
				TRX2000_start.page.hide();
				TRX2000_radar.page.hide();
			}
		} else {
			TRX2000_standby.page.hide();
			TRX2000_start.page.hide();
			TRX2000_radar.page.hide();
		}
	},
};
	
	
var canvas_TRX2000_standby = {
	new: func(canvas_group, file) {
		var m = { parents: [canvas_TRX2000_standby , canvas_TRX2000_base] };
		m.init(canvas_group, file);

		return m;
	},
	getKeys: func() {
		return ["time.utc"];
	},
	update: func() {
		me["time.utc"].setText( sprintf("%02d", time.hour.getIntValue() )~":"~sprintf("%02d", time.minute.getIntValue() )~":"~sprintf("%02d", time.second.getIntValue() ) );
	}
	
};


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

		return m;
	},
	getKeys: func() {
		return ["target0","target0.arrow","target0.sel","target1","target1.arrow","target1.sel","target2","target2.arrow","target2.sel","target3","target3.arrow","target3.sel","target4","target4.arrow","target4.sel","rel_altitude","vs","id","dist","range"];
	},
	update: func() {
		var rel_alt = nil;
		var vs = nil;
		var id = "";
		var dist = nil;
		var nearest_v = nearest.getValue();
		
		var range = range.getValue();
		var children = all_contacts.getChildren();
		var min_dist = 9999999;
		forindex(var key; children){
			if(children[key].getNode("valid").getValue() == 1){
				me["target"~key].show();
				var x = children[key].getNode("x").getValue()/(range*1000);
				var y = children[key].getNode("y").getValue()/(range*1000);
				me["target"~key].setTranslation(x*105,-y*105);
				me["target"~key~".arrow"].setRotation(children[key].getNode("rel_hdg").getValue()*D2R);
				var distance = children[key].getNode("dist").getValue();
				#print(key);
				#print(selected.getValue());
				if(key == selected.getValue() ){
					me["target"~key~".sel"].show();
					rel_alt = children[key].getNode("delta_alt").getValue();
					vs = children[key].getNode("vs").getValue();
					id = children[key].getNode("id").getValue();
					dist = distance
				}else{
					me["target"~key~".sel"].hide();
				}
				if(distance < min_dist){
					nearest_v = key;
					min_dist = distance
				}
			}else{
				if(key <= 4){
					me["target"~key].hide();
				}
			}
		}
		nearest.setValue(nearest_v);
		
		me["rel_altitude"].setText(sprintf("%+4d", rel_alt or 0));
		me["vs"].setText(sprintf("%+2.1f", vs or 0));
		var length = utf8.size(id);
		if(length > 4){
			me["id"].setFontSize(32,1);
		}else{
			me["id"].setFontSize(40,1);
		}
		me["id"].setText(sprintf("%s", id));
		me["dist"].setText(sprintf("%4d", (dist or 0)/1000));
		
		if(range < 1){
			me["range"].setFontSize(30,1);
			me["range"].setText(sprintf("%.1f", range));
		}else{
			me["range"].setFontSize(37,1);
			me["range"].setText(sprintf("%1d", range));			
		}
	}
	
};


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

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

var TRX2000_update = maketimer( 0.02, canvas_TRX2000_base.update );
TRX2000_update.simulatedTime = 1;

setlistener("sim/signals/fdm-initialized", func {
	TRX2000_display = canvas.new({
		"name": "TRX2000",
		"size": [320, 240],
		"view": [320, 240],
		"mipmapping": 1
	});
	TRX2000_display.addPlacement({"node": "display"});
	var groupMain = TRX2000_display.createGroup();
	var groupStart = TRX2000_display.createGroup();
	var groupRadar = TRX2000_display.createGroup();


	TRX2000_radar = canvas_TRX2000_radar.new(groupRadar, instrument_dir~"TRX2000_radar.svg");
	TRX2000_standby = canvas_TRX2000_standby.new(groupMain, instrument_dir~"TRX2000_standby.svg");
	TRX2000_start = canvas_TRX2000_start.new(groupStart, instrument_dir~"TRX2000_start.svg");

	TRX2000_update.start();
});

var showTRX2000 = func {
	var dlg = canvas.Window.new([320, 240], "dialog").set("resize", 1);
	dlg.setCanvas(TRX2000_display);
}

var i=0;

var check_off = func () {
	if( pushknob.getBoolValue() and i<50 ){
		i=i+1;
		settimer(check_off, 0.1);
	}elsif( pushknob.getBoolValue() == 1 and i >= 50 ){
		i=0;
		status = 0; # TODO put proper shutdown routine here later
	}else{
		i=0;
	}
}


setlistener( pushknob, func {
	if( pushknob.getBoolValue() ){
		if( volts.getDoubleValue() > 9 and status == 0 ){
			status = 1;
			settimer( func{ status = 2 }, 3 + rand() );
		}elsif( volts.getDoubleValue() <= 9  and status != 0 ){
			status = 0;
		}
		check_off();
	}
});


setlistener(volts, func{
	if( volts.getDoubleValue() <= 9 and status != 0 ){
		status = 0;
	}
});
