Modifiers = Modifiers or {}

local lastMods = 0
local shiftDown = false
local listeners = {} -- [callback] = true
local pollEvent = nil

local function computeShift(mods)
    return bit.band(mods, KeyboardShiftModifier) ~= 0
end

local function notifyListeners()
    for cb in pairs(listeners) do
        cb(shiftDown)
    end
end

local function pollModifiers()
    local mods = g_keyboard.getModifiers()
    if mods == lastMods then
        return
    end

    lastMods = mods
    local newShift = computeShift(mods)
    if newShift ~= shiftDown then
        shiftDown = newShift
        notifyListeners()
    end
end

function Modifiers.init()
    if pollEvent then return end
    lastMods = g_keyboard.getModifiers()
    shiftDown = computeShift(lastMods)
    pollEvent = cycleEvent(pollModifiers, 15)
end

function Modifiers.isShiftPressed()
    return shiftDown
end

function Modifiers.onShiftChanged(callback)
    if type(callback) ~= 'function' then return end
    Modifiers.init()
    listeners[callback] = true
end

function Modifiers.removeListener(callback)
    listeners[callback] = nil
end
