ittOverride = globalPropertyi("sim/operation/override/override_itt_egt")
throttleOverride = globalPropertyi("sim/operation/override/override_throttles")

itt_left = globalProperty("sim/flightmodel/engine/ENGN_ITT_c[0]")
itt_right = globalProperty("sim/flightmodel/engine/ENGN_ITT_c[1]")

ENGN_thro1 = globalProperty("sim/flightmodel/engine/ENGN_thro_use[0]")
ENGN_thro2 = globalProperty("sim/flightmodel/engine/ENGN_thro_use[1]")
engine_throttle_request1 = globalProperty("sim/cockpit2/engine/actuators/throttle_ratio[0]")
engine_throttle_request2 = globalProperty("sim/cockpit2/engine/actuators/throttle_ratio[1]")

n1_1 = globalProperty("sim/flightmodel/engine/ENGN_N1_[0]")
n1_2 = globalProperty("sim/flightmodel/engine/ENGN_N1_[1]")

trq_max_left = globalProperty("sim/aircraft/controls/acf_trq_max_eng[0]")
trq_max_right = globalProperty("sim/aircraft/controls/acf_trq_max_eng[1]")

trq_curr_left = globalProperty("sim/cockpit2/engine/indicators/torque_n_mtr[0]")
trq_curr_right = globalProperty("sim/cockpit2/engine/indicators/torque_n_mtr[1]")

altitude_ft_pilot = globalProperty("sim/cockpit2/gauges/indicators/altitude_ft_pilot")
airspeed_kts_pilot = globalProperty("sim/cockpit2/gauges/indicators/airspeed_kts_pilot")

w = globalProperty("sim/flightmodel/weight/m_fixed")

starter1 = createGlobalPropertyf("ksgy/L410/starter1")
starter2 = createGlobalPropertyf("ksgy/L410/starter2")

trq1 = createGlobalPropertyf("ksgy/L410/engine/trq1")
trq2 = createGlobalPropertyf("ksgy/L410/engine/trq2")

itt1 = createGlobalPropertyf("ksgy/L410/engine/itt1")
itt2 = createGlobalPropertyf("ksgy/L410/engine/itt2")

eng1fire = globalPropertyi("sim/operation/failures/rel_engfir0")
eng2fire = globalPropertyi("sim/operation/failures/rel_engfir1")

startcommand1 = findCommand("sim/starters/engage_starter_1")
startcommand2 = findCommand("sim/starters/engage_starter_2")

local maxEngineTimeOver100TRQ1 = 360
local maxEngineTimeOver100TRQ2 = 360

-- set(ittOverride, 1)  -- TODO uncomment to use custom ITT
set(throttleOverride, 1)

function onAvionicsDone()
	set(ittOverride, 0)
	set(throttleOverride, 0)
end

function updateITT()
	-- TODO use different value from altitude_ft_pilot
	local i1 = getITT(get(altitude_ft_pilot)/3.28084, get(airspeed_kts_pilot)*1.852, get(engine_throttle_request1))
	local i2 = getITT(get(altitude_ft_pilot)/3.28084, get(airspeed_kts_pilot)*1.852, get(engine_throttle_request2))
	-- set(itt1, i1) -- TODO uncomment to use custom ITT
	-- set(itt2, i2) -- TODO uncomment to use custom ITT
	set(itt1, get(itt_left))
	set(itt2, get(itt_right))
end

function checkEngine()
	-- eng 1
	if get(trq1) >= 100 then
		maxEngineTimeOver100TRQ1 = maxEngineTimeOver100TRQ1 - 1 -- TODO 1 legyen ambient temp fuggo
	else
		maxEngineTimeOver100TRQ1 = maxEngineTimeOver100TRQ1 + 1
	end
	if maxEngineTimeOver100TRQ1 > 360 then maxEngineTimeOver100TRQ1 = 360 end

	if maxEngineTimeOver100TRQ1 <= 0 then
		set(eng1fire, 6)
		maxEngineTimeOver100TRQ1 = 360
	end

	-- eng 2
	if get(trq2) >= 100 then
		maxEngineTimeOver100TRQ2 = maxEngineTimeOver100TRQ2 - 1
	else
		maxEngineTimeOver100TRQ2 = maxEngineTimeOver100TRQ2 + 1
	end
	if maxEngineTimeOver100TRQ2 > 360 then maxEngineTimeOver100TRQ2 = 360 end

	if maxEngineTimeOver100TRQ2 <= 0 then
		set(eng2fire, 6)
		maxEngineTimeOver100TRQ2 = 360
	end
end

function update()
	set(ENGN_thro1, get(engine_throttle_request1))
	set(ENGN_thro2, get(engine_throttle_request2))

	if get(starter1) == 1 then
		commandBegin(startcommand1)
	end
	if get(starter2) == 1 then
		commandBegin(startcommand2)
	end
	
	if get(n1_1) > 60.0 then -- TODO real value: 45
		commandEnd(startcommand1)
		set(starter1, 0)
	end
	
	if get(n1_2) > 60.0 then -- TODO real value: 45
		commandEnd(startcommand2)
		set(starter2, 0)
	end

	set(trq1, get(trq_curr_left)/get(trq_max_left)*100)
	set(trq2, get(trq_curr_right)/get(trq_max_right)*100)

	updateITT()
	updateTimed(checkEngine, 1)
end

function getITT(customALT, customSPD, customTHR)
	-- TODO engine running
	-- TODO start seq
	-- TODO "sim/operation/override/override_fuel_flow"
	-- TODO ha airbleed be van kapcsolva, a max ITT homerseklet novekedes 30 fok lehet!
	-- TODO: water injection: 20-30 fok eses a rendszer bekapocsolasakor
	-- TODO: alapjaraton:   
-- /*
-- 		nG 					60t063% 
-- 		ITT 				max.550°C  //535
-- 		Tq  				min. 8% 
-- 		Oil temperature 	min. +20  OC  (68 OF) 
-- 		Oil pressure  		min. 1.8 kplcm  * (25.6 psi) 
-- 		Propeller speed  	920 +/- 60 RPM 
-- 		)difference between the left and right propeller speed must not exceed 40 RPM) 
-- */
	local ITT
	local THR = customTHR
	local DEFAULT_ITT = 711 - 3*(customSPD/100) --// sebessegfuggoen valtozik az alap ITT - lasd SPEED_COMP
	local spd = customSPD
	local SPEED_COMP = (spd/100)*(spd/100)+(spd/100)*(spd/100) --// 100km/h-kent 3+ fok minusz = 100km/h-3fok 200-6 300-9 400-12 

	-- // ALT: 500m-enkent 10 fok = 1m-enkent ~0.02fok -- beizer: 0.400, 0.225, 0.775, 0.615

	tALT = customALT
	-- //if (tALT>3000) {tALT=3000}
-- /*
-- 		Bezier pontok
--                   b
--                d
--             c
--         a
-- */

	
	local THR_MAX = 1.0
	local THR_CRUISE = 0.8
	local IDLE_ITT = 535

	ax = 0
	function ayF(spd)
		local r_ay = LagrangeInterpolate(THR,710.5,676,IDLE_ITT, THR_MAX,THR_CRUISE,0)
		if (spd > 200) then
			r_ay = r_ay + LagrangeInterpolate(spd,
				LagrangeInterpolate(THR,0,1.5,0, THR_MAX,THR_CRUISE,0),
				LagrangeInterpolate(THR,5,8.5,0, THR_MAX,THR_CRUISE,0),
				LagrangeInterpolate(THR,6,8.7,0, THR_MAX,THR_CRUISE,0),
				200,
				300,
				400)
		end
		return r_ay
	end

	ay = ayF(spd)
	-- //console.log(ay)

	bx = 3000
	function byF(spd)
		local r_by = LagrangeInterpolate(THR,775,745,IDLE_ITT, THR_MAX,THR_CRUISE,0)
		if (spd > 100) then
			r_by = r_by - LagrangeInterpolate(spd, 
				LagrangeInterpolate(THR,0,0,0, THR_MAX,THR_CRUISE,0),
				LagrangeInterpolate(THR,4,6,0, THR_MAX,THR_CRUISE,0),
				LagrangeInterpolate(THR,5,7,0, THR_MAX,THR_CRUISE,0),
				100, 200, 400)
		end
		return r_by
	end
	by = byF(spd)

	cx = LagrangeInterpolate(THR,1800,1000,IDLE_ITT, THR_MAX,THR_CRUISE,0)
	function cyF(spd)
		local r_cy = LagrangeInterpolate(THR,725,687,IDLE_ITT, THR_MAX,THR_CRUISE,0)
		if (spd > 300) then
			r_cy = r_cy + LagrangeInterpolate(spd, 
				LagrangeInterpolate(THR,1,1,0,   THR_MAX,THR_CRUISE,0),
				LagrangeInterpolate(THR,2,7,0,   THR_MAX,THR_CRUISE,0),
				LagrangeInterpolate(THR,3,8,0,   THR_MAX,THR_CRUISE,0),
				200,300,400)
		end
		return r_cy
	end
	cy = cyF(spd)


	dx = LagrangeInterpolate(THR,1800,1950,IDLE_ITT, THR_MAX,THR_CRUISE,0)
	function dyF()
		r_dy = LagrangeInterpolate(THR,745,700,IDLE_ITT, THR_MAX,THR_CRUISE,0)
		if (spd > 100) then
			r_dy = r_dy - LagrangeInterpolate(spd,
				LagrangeInterpolate(THR,0.6,-1,0, THR_MAX,THR_CRUISE,0),
				LagrangeInterpolate(THR,1,-1,0, THR_MAX,THR_CRUISE,0),
				LagrangeInterpolate(THR,1.2,2,0,  THR_MAX,THR_CRUISE,0),
				200,300,400)
			
		end
		return r_dy
	end
	dy = dyF()

	ALT_ITT = BezierGetBezier(
		tALT/LagrangeInterpolate(THR,3000,2800,0,  THR_MAX,THR_CRUISE,0), 
		{x=bx,y=by},
		{x=dx,y=dy},
		{x=cx,y=cy},
		{x=ax,y=ay}
	).y
	

	ALT_MAX_ITT = BezierGetBezier( --// full
		tALT/6000, 
		{x=6000,y=LagrangeInterpolate(THR,735,678,IDLE_ITT,  THR_MAX,THR_CRUISE,0)}, --//b
		{x=4000,y=LagrangeInterpolate(THR,735,675,450,  THR_MAX,THR_CRUISE,0)}, --//d
		{x=2200,y=LagrangeInterpolate(THR,735,675,450,  THR_MAX,THR_CRUISE,0)}, --//c
		{x=200,y=LagrangeInterpolate(THR,735,683,IDLE_ITT,  THR_MAX,THR_CRUISE,0)}   --//a
	).y

	-- // ALT_MAX_ITT = BezierGetBezier( // 0.8
	-- // 	tALT/6000, 
	-- // 	{x:6000,y:678}, //b
	-- // 	{x:4000,y:675}, //d
	-- // 	{x:2200,y:675}, //c
	-- // 	{x:200,y:683}   //a
	-- // ).y
	

	ITT = ALT_ITT - SPEED_COMP

	if (ITT>ALT_MAX_ITT) then
		ITT = ALT_MAX_ITT
	end

	if (ITT>735) then 
		ITT=735
	end
	
	return ITT

end

function LagrangeInterpolate(vx, f1, f2, f3, v1, v2, v3)
	local v1 = v1 or 200
	local v2 = v2 or 300
	local v3 = v3 or 400
	
	local f1 = f1 or 0
	local f2 = f2 or 5
	local f3 = f3 or 6

	local r = ((vx-v2)*(vx-v3))/((v1-v2)*(v1-v3))*f1 + 
			((vx-v1)*(vx-v3))/((v2-v1)*(v1-v3))*f2 + 
			((vx-v1)*(vx-v2))/((v3-v1)*(v3-v2))*f3

	return r
end

function BezierCoord(xc,yc)
    return {
    	x=xc,
    	y=yc
    }
end

function BezierB1(t)
	return t*t*t
end
function BezierB2(t)
	return 3*t*t*(1-t)
end
function BezierB3(t)
	return 3*t*(1-t)*(1-t)
end
function BezierB4(t)
	return (1-t)*(1-t)*(1-t)
end

function BezierGetBezier(percent,C1,C2,C3,C4)
	local pos = BezierCoord()
	pos.x = C1.x*BezierB1(percent) + C2.x*BezierB2(percent) + C3.x*BezierB3(percent) + C4.x*BezierB4(percent)
	pos.y = C1.y*BezierB1(percent) + C2.y*BezierB2(percent) + C3.y*BezierB3(percent) + C4.y*BezierB4(percent)
	return pos
end
