-- Show whether any process blocks automatic idle. The monitor combines logind
-- idle inhibitors with session ScreenSaver requests such as browser video wake locks.
local command = (noctalia.getenv("HOME") or "") .. "/.local/bin/idle-inhibitor-monitor --count"

local request_in_flight = false

function update()
  noctalia.setUpdateInterval(5000)

  if request_in_flight then return end
  request_in_flight = true
  noctalia.runAsync(command, function(result)
    request_in_flight = false

    local count = tonumber(result.stdout)
    if result.exitCode ~= 0 or count == nil then
      barWidget.setGlyph("circle-help")
      barWidget.setText("Idle ?")
      barWidget.setTooltip("Unable to inspect idle inhibitors")
      return
    end

    if count > 0 then
      barWidget.setGlyph("moon-off")
      barWidget.setText(string.format("Idle %d", count))
      barWidget.setTooltip(
        string.format("%d idle inhibitor%s active · click for details", count, count == 1 and "" or "s")
      )
    else
      barWidget.setGlyph("moon")
      barWidget.setText("Idle")
      barWidget.setTooltip("No active idle inhibitors · click for details")
    end
  end)
end

function onClick()
  noctalia.runAsync("noctalia msg panel-toggle alex/system-status:inhibitors-panel")
end
