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

local DEBUG = false         -- Setze auf true, um Debug-Ausgaben zu aktivieren

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

AdBlueRemainingHoursEvent = {}
local AdBlueRemainingHoursEvent_mt = Class(AdBlueRemainingHoursEvent, Event)

InitEventClass(AdBlueRemainingHoursEvent, "AdBlueRemainingHoursEvent")

function AdBlueRemainingHoursEvent.emptyNew()
    local self = Event.new(AdBlueRemainingHoursEvent_mt)
    return self
end

function AdBlueRemainingHoursEvent.new(vehicle, remainingHours)
    local self = AdBlueRemainingHoursEvent.emptyNew()
    self.vehicle = vehicle
    self.remainingHours = remainingHours  -- Kann jetzt Float ODER String sein
    return self
end

function AdBlueRemainingHoursEvent:readStream(streamId, connection)
    self.vehicle = NetworkUtil.readNodeObject(streamId)
    
    -- NEU: Prüfe ob es ein String ist (Flag)
    local isString = streamReadBool(streamId)
    
    if isString then
        self.remainingHours = streamReadString(streamId)
    else
        self.remainingHours = streamReadFloat32(streamId)
    end
    
    self:run(connection)
end

function AdBlueRemainingHoursEvent:writeStream(streamId, connection)
    NetworkUtil.writeNodeObject(streamId, self.vehicle)
    
    -- NEU: Prüfe Typ und sende entsprechend
    local isString = type(self.remainingHours) == "string"
    streamWriteBool(streamId, isString)
    
    if isString then
        streamWriteString(streamId, self.remainingHours)
    else
        streamWriteFloat32(streamId, self.remainingHours)
    end
end

function AdBlueRemainingHoursEvent:run(connection)
    if self.vehicle ~= nil and self.vehicle.spec_adblueConsumer ~= nil then
        local spec = self.vehicle.spec_adblueConsumer
        spec.remainingHours = self.remainingHours
        
        -- Debug-Ausgabe
        if type(self.remainingHours) == "string" then
            dprint(string.format("[AdBlue Client] Remaining Hours synced: %s", self.remainingHours))
        else
            local hours = math.floor(self.remainingHours)
            local minutes = math.floor((self.remainingHours - hours) * 60)
            dprint(string.format("[AdBlue Client] Remaining Hours synced: %d:%02d H (%.2f)", hours, minutes, self.remainingHours))
        end
    end
end