-- ============================================================================
-- === DieselRemainingHoursEvent.lua
-- === Mod by [LSMT] Modding Team 
-- === LS25 /FS25
-- === Script by [LSMT] BaTt3RiE @ 2025
-- === Ver 1.0.0.0
-- === Synchronisiert Diesel remainingHours vom Server zu Clients
-- ============================================================================

local DEBUG = false

local function dprint(...)
    if DEBUG then
        print("[DieselRemainingHoursEvent] " .. string.format(...))
    end
end

DieselRemainingHoursEvent = {}
local DieselRemainingHoursEvent_mt = Class(DieselRemainingHoursEvent, Event)

InitEventClass(DieselRemainingHoursEvent, "DieselRemainingHoursEvent")

function DieselRemainingHoursEvent.emptyNew()
    local self = Event.new(DieselRemainingHoursEvent_mt)
    return self
end

function DieselRemainingHoursEvent.new(vehicle, remainingHours)
    local self = DieselRemainingHoursEvent.emptyNew()
    self.vehicle = vehicle
    self.remainingHours = remainingHours
    return self
end

function DieselRemainingHoursEvent:readStream(streamId, connection)
    self.vehicle = NetworkUtil.readNodeObject(streamId)
    
    local isString = streamReadBool(streamId)
    
    if isString then
        self.remainingHours = streamReadString(streamId)
    else
        self.remainingHours = streamReadFloat32(streamId)
    end
    
    self:run(connection)
end

function DieselRemainingHoursEvent:writeStream(streamId, connection)
    NetworkUtil.writeNodeObject(streamId, self.vehicle)
    
    local isString = type(self.remainingHours) == "string"
    streamWriteBool(streamId, isString)
    
    if isString then
        streamWriteString(streamId, self.remainingHours)
    else
        streamWriteFloat32(streamId, self.remainingHours)
    end
end

function DieselRemainingHoursEvent:run(connection)
    if self.vehicle ~= nil and self.vehicle.spec_motorized ~= nil then
        local spec = self.vehicle.spec_motorized
        spec.dieselRemainingHours = self.remainingHours
        
        dprint(string.format("[Client] Diesel Remaining Hours synced: %s", tostring(self.remainingHours)))
    end
end