-- ============================================================================
-- === MotorizedDieselRange.lua
-- === Mod by [LSMT] Modding Team 
-- === LS25 /FS25
-- === Script by [LSMT] BaTt3RiE @ 2025
-- === Ver 1.0.1.0
-- === Erweitert Motorized um Diesel-Reichweiten-Berechnung
-- ============================================================================

local ModDir = g_currentModDirectory
source(ModDir .. "script/DieselRemainingHoursEvent.lua")

local DEBUG = false  -- Debug-Ausgaben an/aus

local function debugPrint(...)
    if DEBUG then
        print(...)
    end
end

-- Original onLoad erweitern
local originalMotorizedOnLoad = Motorized.onLoad
function Motorized:onLoad(savegame)
    originalMotorizedOnLoad(self, savegame)
    
    local spec = self.spec_motorized
    if spec then
        spec.dieselRemainingHours = 0
        spec.dieselLastUpdateTime = 0
        spec.dieselLastSyncTime = 0
        spec.dieselLastDebugTime = 0
    end
end

-- Original onUpdate erweitern
local originalMotorizedOnUpdate = Motorized.onUpdate
function Motorized:onUpdate(dt, isActiveForInput, isActiveForInputIgnoreSelection, isSelected)
    originalMotorizedOnUpdate(self, dt, isActiveForInput, isActiveForInputIgnoreSelection, isSelected)
    
    local spec = self.spec_motorized
    if not spec then
        return
    end
    
    -- NUR Server berechnet
    if g_server then
        if self:getIsMotorStarted() then
            -- ========================================
            -- Diesel-Verbrauch DIREKT aus lastFuelUsageDisplay holen
            -- ========================================
            local dUsageLh = 0

            -- lastFuelUsageDisplay ist BEREITS in L/h (Giants berechnet es!)
            if spec.lastFuelUsageDisplay and spec.lastFuelUsageDisplay > 0 then
                dUsageLh = spec.lastFuelUsageDisplay
            end

            -- Diesel-Füllstand MIT FALLBACK (wie Giants in SpeedMeterDisplay.lua!)
            local dLvl = 0
            local dIdx = nil
            local fillType = FillType.DIESEL

            -- Methode 1: Nutze getConsumerFillUnitIndex (wie Giants)
            dIdx = self:getConsumerFillUnitIndex(fillType)

            -- Methode 2: Fallback auf ElectricCharge (wie Giants!)
            if dIdx == nil then
                fillType = FillType.ELECTRICCHARGE
                dIdx = self:getConsumerFillUnitIndex(fillType)
            end

            -- Methode 3: Fallback auf Methane (wie Giants!)
            if dIdx == nil then
                fillType = FillType.METHANE
                dIdx = self:getConsumerFillUnitIndex(fillType)
            end

            -- Methode 4: Letzte Rettung - Durchsuche ALLE FillUnits
            if dIdx == nil and self.spec_fillUnit and self.spec_fillUnit.fillUnits then
                for i, fillUnit in pairs(self.spec_fillUnit.fillUnits) do
                    if fillUnit and fillUnit.fillType == FillType.DIESEL then
                        dIdx = i
                        fillType = FillType.DIESEL
                        debugPrint("[Diesel DEBUG] DIESEL über Schleife gefunden! Index=%d", i)
                        break
                    end
                end
            end

            -- Wenn DIESEL gefunden wurde, hole FillLevel
            if dIdx and self.spec_fillUnit and self.spec_fillUnit.fillUnits[dIdx] then
                local fillUnit = self.spec_fillUnit.fillUnits[dIdx]
                dLvl = fillUnit.fillLevel or 0
                
                -- Validierung: Nur plausible Werte
                if dLvl >= 0 and dLvl <= (fillUnit.capacity or 10000) then
                    spec.dieselLastValidFillLevel = dLvl
                else
                    -- Fallback: Nutze letzten gültigen Wert
                    dLvl = spec.dieselLastValidFillLevel or 0
                    debugPrint(string.format("[Diesel WARNING] Ungültiger FillLevel: %.2f (nutze cached: %.2f)", 
                        fillUnit.fillLevel or -1, dLvl))
                end
            else
                -- Kein DIESEL-Tank gefunden
                if (not spec.dieselLastDebugTime) or (g_currentMission.time > spec.dieselLastDebugTime + 5000) then
                    debugPrint("[Diesel ERROR] Kein DIESEL-Tank gefunden! (getConsumerFillUnitIndex gibt nil)")
                end
                dLvl = spec.dieselLastValidFillLevel or 0
            end
            
            local criticalThreshold = 0.01
            
            -- Berechne dieselRemainingHours NUR auf Server (alle 1 Sekunde)
            local UPDATE_INTERVAL = 1000
            if (not spec.dieselLastUpdateTime) or (g_currentMission.time > spec.dieselLastUpdateTime + UPDATE_INTERVAL) then
                if dUsageLh > 0.0001 and dLvl > criticalThreshold then
                    spec.dieselRemainingHours = dLvl / dUsageLh
                else
                    spec.dieselRemainingHours = dLvl <= criticalThreshold and 0 or math.huge
                end
                spec.dieselLastUpdateTime = g_currentMission.time
            end
            
            -- Sync an Clients NUR alle 1 Sekunde
            local SYNC_INTERVAL = 1000
            if (not spec.dieselLastSyncTime) or (g_currentMission.time > spec.dieselLastSyncTime + SYNC_INTERVAL) then
                local valueToSync = spec.dieselRemainingHours or 0
                
                if valueToSync == math.huge then
                    valueToSync = "--:--"
                end
                
                g_server:broadcastEvent(DieselRemainingHoursEvent.new(self, valueToSync))
                spec.dieselLastSyncTime = g_currentMission.time
                
                debugPrint(string.format("[Diesel Server] Synced remainingHours: %s", tostring(valueToSync)))
            end
            
            -- Debug NUR alle 1 Sekunde
            if (not spec.dieselLastDebugTime) or (g_currentMission.time > spec.dieselLastDebugTime + 100) then
                if spec.dieselRemainingHours and spec.dieselRemainingHours ~= math.huge and spec.dieselRemainingHours > 0 then
                    local hours = math.floor(spec.dieselRemainingHours)
                    local minutes = math.floor((spec.dieselRemainingHours - hours) * 60)
                    debugPrint(string.format("[Diesel] Remaining: %d:%02d H (%.6f L, %.4f L/h)", 
                        hours, minutes, dLvl, dUsageLh))
                end
                spec.dieselLastDebugTime = g_currentMission.time
            end
        else
            -- Motor aus
            spec.dieselRemainingHours = math.huge
            
            if (not spec.dieselLastSyncTime) or (g_currentMission.time > spec.dieselLastSyncTime + 5000) then
                g_server:broadcastEvent(DieselRemainingHoursEvent.new(self, "--:--"))
                spec.dieselLastSyncTime = g_currentMission.time
                debugPrint("[Diesel Server] Motor AUS - Synced: --:--")
            end
        end
    end
end