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

OPENING_SPEED   = GetFloatParam("opening_speed", 1.1)
CLOSING_SPEED   = GetFloatParam("closing_speed", 1.6)

function init()
    hinges = FindJoints()
    v_b = nil
    for i = 1, #hinges do
        local handle = hinges[i]
        local min, max = GetJointLimits(handle)
        local body = GetShapeBody(GetJointShapes(handle)[1])
        v_b = v_b or GetVehicleBody(GetBodyVehicle(body)) -- get main vehicle body
        hinges[i] = {
            handle = handle,
            body = body,
            min = min,
            max = max,
        }
    end
    activated = false
    disabled = false
    reached_max = false
    motorSound = LoadLoop("vehicle/hydraulic-loop.ogg")
end

function update(dt)
    if disabled then return end

    if not activated and HasTag(v_b, "autobreak") then
        for j = #hinges, 1, -1 do
            local hinge = hinges[j]
            local handle = hinge.handle
            if IsJointBroken(handle) then
                table.remove(hinges, j)
                if #hinges == 0 then
                    disabled = cEntity:EnqueueDeletion()
                    return
                end
            else
                SetJointMotorTarget(handle, hinge.max, OPENING_SPEED)
            end
        end
        activated = true
    elseif activated and not HasTag(v_b, "autobreak") then
        for j = #hinges, 1, -1 do
            local hinge = hinges[j]
            local handle = hinge.handle
            if IsJointBroken(handle) then
                table.remove(hinges, j)
                if #hinges == 0 then
                    disabled = cEntity:EnqueueDeletion()
                    return
                end
            else
                SetJointMotorTarget(handle, hinge.min, CLOSING_SPEED)
            end
        end
        activated = false
    end

    if not reached_max and activated then
        local hinge = hinges[1]
        local handle = hinge.handle
        local max = hinge.max
        local movement = GetJointMovement(handle)
        if movement >= (max - 0.01) then
            reached_max = true
        else
            PlayLoop(motorSound, GetBodyTransform(hinge.body).pos, 0.2, true, 0.8)
            reached_max = nil
        end
    elseif reached_max ~= false and not activated then
        local hinge = hinges[1]
        local handle = hinge.handle
        local min = hinge.min
        local movement = GetJointMovement(handle)
        if movement <= (min + 0.01) then
            reached_max = false
        else
            local body = hinge.body
            SetBodyActive(body, true)
            PlayLoop(motorSound, GetBodyTransform(body).pos, 0.2, true, 0.8)
        end
    end
end
