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

shape = nil
body = nil
joint = nil
joint_mi, joint_ma = nil, nil
disabled = nil
mission = nil

function init()
    shape = FindShape()
    body = GetShapeBody(shape)
    joint = FindJoint()
    joint_mi, joint_ma = GetJointLimits(joint)
end

function tick(dt)
    if disabled then return end

    if not mission then
        mission = GetString("level.mission")
        if mission ~= "bluetide" then
            SetTag(shape, "interact", "loc@START")
            SetDescription(shape, "")
        end
    end
    if not IsHandleValid(shape) or IsShapeBroken(shape) then
        disabled = cEntity:EnqueueDeletion()
        SetBodyDynamic(body, true)
        SetBodyActive(body, true)
        SetJointMotorTarget(joint, joint_ma, 2)
        return
    end
    if GetPlayerInteractShape() == shape and InputPressed("interact") then
        local interactTag = GetTagValue(shape, "interact")
        if interactTag == "loc@START" then
            TriggerEvent(EVENTS.CALL_FUNCTION, "set_tag;grinder;speed;-3;")
            TriggerEvent(EVENTS.CALL_FUNCTION, "set_tag;grinder2;speed;3;")
            SetTag(shape, "interact", "loc@STOP")
            JointMove()
        elseif interactTag == "loc@STOP" then
            TriggerEvent(EVENTS.CALL_FUNCTION, "set_tag;grinder;speed;0;")
            TriggerEvent(EVENTS.CALL_FUNCTION, "set_tag;grinder2;speed;0;")
            SetTag(shape, "interact", "loc@START")
            JointMove()
        end
    end
end

function JointMove()
    local cur = GetJointMovement(joint)
    local target = tonumber(cur >= joint_ma - 0.001 and joint_mi or joint_ma)
    SetBodyDynamic(body, true)
    SetBodyActive(body, true)
    SetJointMotorTarget(joint, target, 2)
end
