-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
--EQUIPMENT DEFECT DETECTOR ENGINE SCRIPT INJECTION--------------------------------------------------------------------------------------------------------------------
--(c)Searchlight Simulations 2020, OPEN SOURCE-------------------------------------------------------------------------------------------------------------------------

--THIS LOADS UP THE ORIGINAL (RENAMED) ENGINE SCRIPT.
require("Assets/RSC/PacificSurfliner/RailVehicles/Diesel/F59PHI/Default/Engine/EngineScriptNew.out.prev")

--EXAMPLES PATHS:
--DEFAULT KUJU SD40-2
--require("Assets/Kuju/RailsimulatorUS/RailVehicles/Diesel/SD40-2/Default/Engine/SD40-2EngineScript.lua.prev")

--RSC SHERMAN HILL ES44AC
--require("Assets/RSC/ShermanHill/RailVehicles/Diesel/ES44AC/Default/CommonScripts/ES44ACEngineScript.out.prev")

--CHECK THE ORIGINAL ENGINE SCRIPT FOR DEFAULT FUNCTIONS
Prev_Initialise = Initialise
Prev_OnControlValueChange = OnControlValueChange
Prev_Update = Update
Prev_OnConsistMessage = OnConsistMessage
Prev_OnCustomSignalMessage = OnCustomSignalMessage
Prev_OnSave = OnSave
Prev_OnResume = OnResume

--THE AXLE COUNT OF THIS LOCOMOTIVE. ADJUST BOTH VALUES BELOW (IF REQUIRED).
--USED WHEN THIS LOCOMOTIVE IS PLAYER CONTROLLED AND LEADING.
AXLE_COUNT_THIS_RV = 4
--USED WHEN THIS LOCOMOTIVE IS PART OF A PLAYER CONTROLLED CONSIST BUT NOT LEADING.
AXLE_COUNT = 4

AXLE_COUNT_ID_OLD = 0
AXLE_COUNT_TOTAL = 0
CAR_COUNT_TOTAL = 0

MSG_ID_INITIAL_CONSIST_MESSAGE = false

function Initialise()
    if Prev_Initialise then
	    Prev_Initialise()
	end
	
	--ASSIGN UNIQUE MESSAGE ID FOR EACH CAR
    CAR_ID = math.random(100000,999999)
	
    Call ( "BeginUpdate" )	
end

function OnControlValueChange(name, index, value)	
    if Prev_OnControlValueChange then
	    Prev_OnControlValueChange(name, index, value)	
	end
end

function Update(time)

    if Prev_Update then
	    Prev_Update(time)	
	end

end


function OnConsistMessage(msg, argument, direction)

    if Prev_OnConsistMessage then
	    Prev_OnConsistMessage(msg, argument, direction)
	end
	
	if Call("GetIsEngineWithKey") == 1 then	
    	--AXLE COUNT ON EQUIPMENT DEFECT DETECTOR DETECTION
		if msg >= 100000 and msg <= 999999 then
	    	if msg ~= AXLE_COUNT_ID_OLD then
		    	AXLE_COUNT_TOTAL = AXLE_COUNT_TOTAL + tonumber(argument)
			
				CAR_COUNT_TOTAL = CAR_COUNT_TOTAL + 1
				TRAIN_SPEED = math.floor(math.abs(Call("GetSpeed") * 2.23694))
	        	TRAIN_LENGTH = math.floor(Call( "GetConsistLength" ) * 3.28084)
	
				AXLE_COUNT_ID_OLD = msg
			end
		end
	
		WRITE_EDD_LAST_TRAIN_INFO()
	
	end
	
	--MESSAGE 00001 IS SENT BY THE LEAD LOCOMOTIVE ONCE IT'S FIRST AXLE PASSES A EQUIPMENT DEFECT DETECTOR DETECTION POINT.
	--ONLY SENT THIS MESSAGE BACK TO THE LEAD ENGINE IF THIS LOCOMOTIVE IS NOT PART OF AN AI-CONSIST AND NOT PLAYER DRIVEN.
	if Call("GetIsPlayer") == 1 then
	    if Call("GetIsEngineWithKey") == 0 then
	        if msg == 00001 then
	            --SEND UNIQUE ID'ED MESSAGE WITH AXLE COUNT BACK TO THE LEAD LOCOMOTIVE
		        Call( "SendConsistMessage", CAR_ID, AXLE_COUNT, 0 )
		        Call( "SendConsistMessage", CAR_ID, AXLE_COUNT, 1 )
			end
		end
	end

	Call( "SendConsistMessage", msg, argument, direction )

end

function OnCustomSignalMessage(ConsistMessage)

    if Prev_OnCustomSignalMessage then
	    Prev_OnCustomSignalMessage(ConsistMessage)
	end
	
	-- "00001" IS SENT BY THE DEFECT DETECTOR ONCE THE FIRST AXLE PASSES THE DETECTION POINT
	if (ConsistMessage == "00001") then

	    AXLE_COUNT_TOTAL = 0
	    CAR_COUNT_TOTAL = 0
		
		--SEND MESSAGE TO TRAILING LOCOMOTIVES AND CARS. THIS FUNCTION IS ONLY EXECUTED ON THE LEAD LOCOMOTIVE, THUS SENT A CONSIST MESSAGE ONLY IN THE OPPOSITE DIRECTION OF TRAVEL.
		Call( "SendConsistMessage", 00001, "", 1 )
	end
end

function OnSave()
    if Prev_OnSave then
	    Prev_OnSave()
	end    
end


function OnResume()
    if Prev_OnResume then
	    Prev_OnResume()
	end 
end


function WRITE_EDD_LAST_TRAIN_INFO()

    --WRITE DATA TO FILE EVERY TIME THE LEAD AXLE PASSES AN EQUIPMENT DEFECT DETECTOR DETECTION POINT
    file = io.open("Assets/SearchlightSimulations/Common/RailNetwork/Signals/DefectDetector/EDD_LAST_TRAIN_INFO.lua", "w")
	
	if (AXLE_COUNT_THIS_RV + AXLE_COUNT_TOTAL) < 10 then
        file:write(AXLE_COUNT_THIS_RV + AXLE_COUNT_TOTAL)
		file:write("XXX")
	elseif (AXLE_COUNT_THIS_RV + AXLE_COUNT_TOTAL) >= 10 and (AXLE_COUNT_THIS_RV + AXLE_COUNT_TOTAL) < 100 then
        file:write(AXLE_COUNT_THIS_RV + AXLE_COUNT_TOTAL)
		file:write("XX")	
	elseif (AXLE_COUNT_THIS_RV + AXLE_COUNT_TOTAL) >= 100 and (AXLE_COUNT_THIS_RV + AXLE_COUNT_TOTAL) < 1000 then
        file:write(AXLE_COUNT_THIS_RV + AXLE_COUNT_TOTAL)
		file:write("X")		
	elseif (AXLE_COUNT_THIS_RV + AXLE_COUNT_TOTAL) >= 1000 then
        file:write(AXLE_COUNT_THIS_RV + AXLE_COUNT_TOTAL)
    end		
	file:write(",")
	if TRAIN_SPEED < 10 then
		file:write("X")
		file:write("X")
        file:write(TRAIN_SPEED)
	elseif TRAIN_SPEED >= 10 and TRAIN_SPEED < 100 then
	    file:write("X")
        file:write(TRAIN_SPEED)
	elseif TRAIN_SPEED >= 100 then
        file:write(TRAIN_SPEED)	
    end	
	file:write(",")
	if TRAIN_LENGTH < 10 then
        file:write(TRAIN_LENGTH)
		file:write("XXXX")
	elseif TRAIN_LENGTH >= 10 and (TRAIN_LENGTH) < 100 then
        file:write(TRAIN_LENGTH)
		file:write("XXX")	
	elseif TRAIN_LENGTH >= 100 and (TRAIN_LENGTH) < 1000 then
        file:write(TRAIN_LENGTH)
		file:write("XX")		
	elseif TRAIN_LENGTH >= 1000 and (TRAIN_LENGTH) < 10000 then
        file:write(TRAIN_LENGTH)
		file:write("X")
    elseif TRAIN_LENGTH >= 10000 and (TRAIN_LENGTH) < 100000 then	
        file:write(TRAIN_LENGTH)
	end
	file:write(",")
	if CAR_COUNT_TOTAL < 10 then
        file:write(CAR_COUNT_TOTAL)
		file:write("XXX")
	elseif CAR_COUNT_TOTAL >= 10 and CAR_COUNT_TOTAL < 100 then
        file:write(CAR_COUNT_TOTAL)
		file:write("XX")	
	elseif CAR_COUNT_TOTAL >= 100 and CAR_COUNT_TOTAL < 1000 then
        file:write(CAR_COUNT_TOTAL)
		file:write("X")		
	elseif CAR_COUNT_TOTAL >= 1000 then
        file:write(CAR_COUNT_TOTAL)
    end	
    file:close()
end