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

thresherJoints = nil
triggerShape = nil
combine = nil
triggered = nil
firstTrigger = nil
main_shape = nil
main_Y = nil
snd = nil
vol = nil
disabled = nil
is_sandbox = nil

function init()
    thresherJoints = FindJoints("thresher")
    triggerShape = FindShape("trigger")
    combine = FindVehicle()
    triggered = false
    firstTrigger = false
    main_shape = GetJointShapes(thresherJoints[1])[2]
    main_Y = select(2, GetShapeSize(main_shape))
    snd = LoadLoop("MOD/snd/blades.ogg")
    vol = 0.5
    disabled = false
    is_sandbox = GetBool("level.sandbox")
end

function tick(dt)
    if firstTrigger then
        if not (is_sandbox and GetPlayerVehicle() == combine) then
            if GetVehicleHealth(combine) > 0 then
                DriveVehicle(combine, 1.0, 0, false)
            else
                firstTrigger = nil
                cEntity:EnqueueDeletion()
                disabled = true
            end
        end

        local joints_exists = #thresherJoints > 0
        if not disabled and joints_exists then
            PlayLoop(snd, GetVehicleTransform(combine).pos, vol)
        end
    end
end

function update(dt)
    if firstTrigger == false and not IsHandleValid(triggerShape) or IsShapeBroken(triggerShape) then
        firstTrigger = true
    end

    if firstTrigger then
        if disabled then return end

        local new_Y = select(2, GetShapeSize(main_shape))
        -- Thresher
        for i=#thresherJoints, 1, -1 do
            local joint = thresherJoints[i]

            if #GetJointShapes(joint) ~= 2 or main_Y-new_Y >= 20 then
                table.remove(thresherJoints, i)
                Delete(joint)
            else
                SetJointMotor(joint, 10.0)
            end
        end

        if #thresherJoints == 0 then
            disabled = true
        end
    end
end
