CompressorICSound = {}

function CompressorICSound.prerequisitesPresent(specializations)
    return true
end

function CompressorICSound.registerEventListeners(vehicleType)
    SpecializationUtil.registerEventListener(vehicleType, "onLoad", CompressorICSound)
    SpecializationUtil.registerEventListener(vehicleType, "onDelete", CompressorICSound)
    SpecializationUtil.registerEventListener(vehicleType, "onUpdateTick", CompressorICSound)
end

function CompressorICSound:onLoad(savegame)
    local spec = {}
    self.spec_compressorICSound = spec

    spec.sample = nil
    spec.isPlaying = false

    local sampleXml = loadXMLFileFromMemory("compressorICSound", [[
<vehicle>
    <compressorSound>
        <sound file="assets/sournd/air_compressor_run.ogg" linkNode="0>0|9|0|7|17" volumeScale="0.56" />
    </compressorSound>
</vehicle>
]])

    if sampleXml ~= nil and sampleXml ~= 0 then
        spec.sample = g_soundManager:loadSampleFromXML(sampleXml, "vehicle.compressorSound", "sound", self.baseDirectory, self.components, 0, AudioGroup.VEHICLE, self.i3dMappings, self)
        delete(sampleXml)
    end
end

function CompressorICSound:onDelete()
    local spec = self.spec_compressorICSound
    if spec ~= nil and spec.sample ~= nil then
        if spec.isPlaying then
            g_soundManager:stopSample(spec.sample)
        end

        g_soundManager:deleteSample(spec.sample)
        spec.sample = nil
        spec.isPlaying = false
    end
end

function CompressorICSound:onUpdateTick(dt, isActiveForInput, isActiveForInputIgnoreSelection, isSelected)
    local spec = self.spec_compressorICSound
    if spec == nil or spec.sample == nil or self.getAnimationTime == nil then
        return
    end

    local animTime = self:getAnimationTime("groupCharge") or 0
    local shouldPlay = animTime > 0.01

    if shouldPlay and not spec.isPlaying then
        g_soundManager:playSample(spec.sample)
        spec.isPlaying = true
    elseif not shouldPlay and spec.isPlaying then
        g_soundManager:stopSample(spec.sample)
        spec.isPlaying = false
    end
end
