--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
-- PZB 500Hz Speed Warning Inductor
-- (goes 150 - 250m before the TSR - Lf2)
-- KUJU / Rail Simulator
--------------------------------------------------------------------------------------

-- debugging stuff
DEBUG = false 					-- set to true to turn debugging on

function DebugPrint( message )
	if (DEBUG) then
		Print( message )
	end
end

-- global constants
-- Signal States
CLEAR 				= 0
WARNING 			= 1
BLOCKED 			= 2

-- Consist Messages

-- Default Stock
MSG_DF_PZB1000		= "1000"
MSG_DF_PZB2000		= "2000"

-- vR Expert Line Stock
CUSTOM_MESSAGE 		= 15;
MSG_VR_PZB500		= "PZB500";
MSG_VR_PZB1000 		= "PZB1000";
MSG_VR_PZB2000 		= "PZB2000";

--------------------------------------------------------------------------------------
-- INITIALISE
--
function Initialise ()
	DebugPrint( ("DEBUG: Initialise") )
	mDone = 0
end

--------------------------------------------------------------------------------------
-- ON CONSIST PASS
--
function OnConsistPass ( prevFrontDist, prevBackDist, frontDist, backDist, linkIndex )

	--DebugPrint( ("DEBUG: OnConsistPass ( pfd " .. prevFrontDist .. ", pbd " .. prevBackDist .. ", fd " .. frontDist .. ", bd " .. backDist .. ", li " .. linkIndex .. ")" ))
	-- if the consist is crossing the inductor now
	if ( frontDist > 0 and backDist < 0 ) or ( frontDist < 0 and backDist > 0 ) then
	
		-- if the consist was previously before siganl then the crossing has just started
		if (prevFrontDist > 0 and prevBackDist > 0) then
			
			if (mDone ~= 1) then
			
				mDone = 1
				
				DebugPrint( ("DEBUG: PZB 500Hz Speed Reduction OnConsistPass: Crossing started") )
				Call( "SendConsistMessage", CUSTOM_MESSAGE,  MSG_VR_PZB500 )
			end
		end
	else
		-- Reset once train has passed
		if (mDone ~= 0) then
			DebugPrint( ("DEBUG: PZB 1000Hz Speed Reduction OnConsistPass: Crossing finished") )
			mDone = 0
		end
	end
end

--------------------------------------------------------------------------------------
-- ON SIGNAL MESSAGE
--
function OnSignalMessage( message, parameter, direction, linkIndex )

	-- Forward every message unchanged, unless it's from a train straddling our link
	if ( parameter ~= "DoNotForward" ) then
		Call( "SendSignalMessage", message, parameter, -direction, 1, linkIndex )
	end
end

--------------------------------------------------------------------------------------
-- JUNCTION STATE CHANGE
-- Left blank - PZB inductors always only have one link
--
function OnJunctionStateChange( junction_state, parameter, direction, linkIndex )
	
end


