#include "../../script/helpers/entity.lua"

rollers = nil
snd = nil
vol = nil
pos = nil
last_active = nil
disabled = nil

function init()
    rollers     = FindJoints("roller")
    snd         = LoadLoop("MOD/snd/grinder.ogg")
    vol         = 1.0
    local sound_loc = FindLocation("sound_pos")
    pos         = sound_loc > 0 and GetLocationTransform(sound_loc).pos
    Delete(sound_loc)
    last_active = nil
    for i = 1, #rollers do
        _G["last_speed"..i] = 0
        _G["speed_change"..i] = nil
    end
end

function tick(dt)
    if disabled then return end

    local is_enabled = false
    local active
    for i=#rollers, 1, -1 do repeat
        local hinge = rollers[i]
        if IsJointBroken(hinge) then
            table.remove(rollers, i)
            if #rollers == 0 then
                disabled = cEntity:EnqueueDeletion()
            end
            break
        end
        local this_enabled = false
        local last_speed = _G["last_speed"..i]
        local speed_change = _G["speed_change"..i]
        local speed = HasTag(hinge, "speed") and tonumber(GetTagValue(hinge, "speed"))
        if speed and last_speed ~= speed then
            _G["speed_change"..i] = last_speed
            SetValue("speed_change"..i, speed, "cosine", 3)
        end
        if not speed or speed ~= 0 then
            is_enabled, this_enabled = true, true
            active = true
        end
        if last_active ~= active then
            if this_enabled then
                SetTag(hinge, "active")
            else
                RemoveTag(hinge, "active")
            end
        end
        SetJointMotor(hinge, speed_change or speed or 3.0)

        _G["last_speed"..i] = speed
    until true end
    last_active = active

    if is_enabled and not GetBool("cinematic.is_credits") then
        PlayLoop(snd, pos, vol)
    end
end
