local MAJOR, MINOR = "LibMatic-SoundThrottle-1.0", 1
assert(LibStub, MAJOR .. " requires LibStub")
local lib = LibStub:NewLibrary(MAJOR, MINOR)
if not lib then return end

local GetTime = GetTime
local PlaySoundFile = PlaySoundFile
local PlaySoundKit = PlaySound

local WINDOW = 2 -- seconds between sounds per key

lib.lastPlayedAt = lib.lastPlayedAt or {}

function lib:Allow(key, now)
    key = key or "global"
    now = now or (GetTime and GetTime()) or 0
    local last = lib.lastPlayedAt[key]
    if last and (now - last) < WINDOW then return false end
    lib.lastPlayedAt[key] = now
    return true
end

function lib:Play(key, sound, channel)
    if not sound or not PlaySoundFile then return false end
    if not self:Allow(key) then return false end
    local ok, willPlay, handle
    if channel then
        ok, willPlay, handle = pcall(PlaySoundFile, sound, channel)
    else
        ok, willPlay, handle = pcall(PlaySoundFile, sound)
    end
    if not ok or not willPlay then return false end
    return true, handle
end

function lib:PlayKit(key, soundKitID, channel)
    if not soundKitID or not PlaySoundKit then return false end
    if not self:Allow(key) then return false end
    local ok, willPlay, handle
    if channel then
        ok, willPlay, handle = pcall(PlaySoundKit, soundKitID, channel)
    else
        ok, willPlay, handle = pcall(PlaySoundKit, soundKitID)
    end
    if not ok or not willPlay then return false end
    return true, handle
end
