local BATTERY_THRESHOLD_1 = 20  -- First threshold for notification
local BATTERY_THRESHOLD_2 = 10  -- Second threshold for critical notification
local ICON_BATTERY_20 = 6355    -- Icon for battery level < 20%
local ICON_BATTERY_10 = 6354    -- Icon for battery level < 10%


return {
    active = true,
    
    on = {
        timer = {
            'every 1 hours'
        }
    },

    logging = {
        level = domoticz.LOG_INFO,
        marker = "AWTRIX3_BATTERY"
    },

    execute = function(domoticz)
        -- Filter devices with low battery level
        local lowOnBattery = domoticz.devices().filter(function(device)
            local level = device.batteryLevel
            return (
                level ~= nil and       -- Ensure the device has a battery level attribute
                level ~= 255 and       -- Ignore if no battery measurement is applicable
                level < BATTERY_THRESHOLD_1 -- Notify if below 20%
            )
        end)

        -- Send individual notifications for each device with low battery
        lowOnBattery.forEach(
            function(lowDevice)
                local batteryLevel = lowDevice.batteryLevel
                local notificationIcon = nil
                
                -- Determine the appropriate icon based on battery level
                if batteryLevel < BATTERY_THRESHOLD_2 then
                    notificationIcon = ICON_BATTERY_10
                else
                    notificationIcon = ICON_BATTERY_20
                end

                local message = lowDevice.name .. " low"
                local payload = {
                    text = message,
                    icon = notificationIcon
                }
                local payloadJSON = domoticz.utils.toJSON(payload)
                domoticz.log('Low battery warning for: ' .. message, domoticz.LOG_INFO)
                domoticz.log("Sending to AWTRIX3: " .. payloadJSON, domoticz.LOG_INFO)
                
                -- Send the notification to AWTRIX3
                local awtrixDevice = domoticz.devices('AWTRIX3 - Send Notification')
                if awtrixDevice then
                    awtrixDevice.setDescription(payloadJSON)
                    awtrixDevice.switchOn().afterSec(2)
                else
                    domoticz.log("AWTRIX3 - Send Notification device not found", domoticz.LOG_ERROR)
                end
            end
        )
    end
}