<%
' Cached Zabbix API wrapper for ALL supply levels (toner, ink, drums, maintenance kits, etc.)
%>
<!--#include file="./zabbix_all_supplies.asp"-->
<%

' Cached function for all supply levels - returns data immediately, refreshes in background if stale
Function GetAllPrinterSuppliesCached(hostIP)
    Dim cacheKey, cacheAge, forceRefresh
    cacheKey = "zabbix_all_supplies_" & hostIP

    ' Check if manual refresh was requested
    forceRefresh = (Request.QueryString("refresh") = "1" And Request.QueryString("ip") = hostIP)

    If forceRefresh Then
        ' Clear cache for manual refresh
        Application.Lock
        Application(cacheKey) = Empty
        Application(cacheKey & "_time") = Empty
        Application(cacheKey & "_refreshing") = "false"
        Application.Unlock
    End If

    ' Check if cache exists
    If Not IsEmpty(Application(cacheKey)) And Not forceRefresh Then
        cacheAge = DateDiff("n", Application(cacheKey & "_time"), Now())

        ' If cache is stale (>5 min) AND not already refreshing, trigger background update
        If cacheAge >= 5 And Application(cacheKey & "_refreshing") <> "true" Then
            ' Mark as refreshing
            Application.Lock
            Application(cacheKey & "_refreshing") = "true"
            Application.Unlock

            ' Trigger async background refresh (non-blocking)
            On Error Resume Next
            Dim http
            Set http = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
            http.Open "GET", "http://localhost/refresh_all_supplies_cache.asp?ip=" & Server.URLEncode(hostIP), True
            http.Send
            Set http = Nothing
            On Error Goto 0
        End If

        ' Return cached data immediately
        GetAllPrinterSuppliesCached = Application(cacheKey)
        Exit Function
    End If

    ' No cache exists - fetch initial data
    Dim freshData, zabbixConnected, pingStatus, suppliesJSON

    zabbixConnected = ZabbixLogin()

    If zabbixConnected = "1" Then
        pingStatus = GetPrinterPingStatus(hostIP)
        suppliesJSON = GetAllPrinterSupplies(hostIP)
    Else
        pingStatus = "-1"
        suppliesJSON = ""
    End If

    ' Store as array: [connected, pingStatus, suppliesJSON]
    Dim resultData(2)
    resultData(0) = zabbixConnected
    resultData(1) = pingStatus
    resultData(2) = suppliesJSON

    ' Cache the result
    Application.Lock
    Application(cacheKey) = resultData
    Application(cacheKey & "_time") = Now()
    Application(cacheKey & "_refreshing") = "false"
    Application.Unlock

    GetAllPrinterSuppliesCached = resultData
End Function

%>
