-- Author: stefan750

local M = {}

local dequeue = require('dequeue')

local bounceAnimTime = 0.5 -- Time after which to reset the ambient animation for mushrooms
local soundPoolSize = 20   -- Amount of preloaded sound sources that can play simultaneously

local bounceSoundId = 1
local bounceSoundPool = {}
local restartAnimQueue = dequeue.new()
local timer = 0

local function onExtensionLoaded()
    for i = 1, soundPoolSize do
        bounceSoundPool[i] = Engine.Audio.createSource("AudioDefault3D", "/levels/mushroomgorge/art/sound/Bounce.ogg")
    end
end

local function onExtensionUnloaded()
    for i = 1, soundPoolSize do
        Engine.Audio.deleteSource(bounceSoundPool[i])
    end
end

local function onUpdate(dtReal, dtSim, dtRaw)
    timer = timer + dtReal

    local queueNext = restartAnimQueue:peek_left()
    if queueNext and queueNext[2] <= (timer - bounceAnimTime) then
        local obj = scenetree.findObjectById(queueNext[1])
        if obj then
            obj:playAnim("ambient")
        end

        restartAnimQueue:pop_left()
    end
end

local function onVehicleSpawned(vehicleId)
    local veh = be:getObjectByID(vehicleId)

    if not veh then
        log("E", "mushroomgorge.onVehicleSpawned", "Vehicle " .. tostring(vehicleId) .. "not found.")
        return
    end

    veh:queueLuaCommand("extensions.loadModulesInDirectory('lua/vehicle/extensions/mushroomgorge')")
end

-- Play animation and sound for bouncing on mushrooms
local function bounceMushroom(name)
    local obj = scenetree[name]

    if not obj then
        log("E", "mushroomgorge.bounceMushroom", "Map object " .. tostring(name) .. "not found.")
        return
    end

    local sound = scenetree.findObjectById(bounceSoundPool[bounceSoundId])
    if sound then
        sound:setTransform(obj:getTransform())
        sound:setVolume(0.5)
        sound:setParameter("pitch", 0.9 + math.random() * 0.2)
        sound:play(-1)
    end
    bounceSoundId = (bounceSoundId % soundPoolSize) + 1

    obj:playAnim("bounce")
    restartAnimQueue:push_right({obj:getId(), timer})
end

M.onExtensionLoaded   = onExtensionLoaded
M.onExtensionUnloaded = onExtensionUnloaded
M.onUpdate            = onUpdate
M.onVehicleSpawned    = onVehicleSpawned
M.bounceMushroom      = bounceMushroom

return M
