GroundLockOnFold = {}

function GroundLockOnFold.prerequisitesPresent(specializations)
    return true
end

function GroundLockOnFold.registerEventListeners(vehicleType)
    SpecializationUtil.registerEventListener(vehicleType, "onLoad", GroundLockOnFold)
    SpecializationUtil.registerEventListener(vehicleType, "onUpdate", GroundLockOnFold)
    SpecializationUtil.registerEventListener(vehicleType, "onDelete", GroundLockOnFold)
end

function GroundLockOnFold:onLoad(savegame)
    self.spec_groundLockOnFold = {
        isLocked = false,
        lastCheckMs = 0
    }
end

local function hasPhysicsAuthority(self)
    return self.isServer ~= false
end

local function getIsMoving(self)
    if self.getLastSpeed ~= nil then
        return math.abs(self:getLastSpeed()) > 0.2
    end

    return false
end

local function setBodyDynamic(self)
    local spec = self.spec_groundLockOnFold
    if spec == nil or not spec.isLocked then
        return
    end

    if not hasPhysicsAuthority(self) then
        spec.isLocked = false
        return
    end

    pcall(setRigidBodyType, self.rootNode, RigidBodyType.DYNAMIC)
    spec.isLocked = false
end

local function setBodyKinematic(self)
    local spec = self.spec_groundLockOnFold
    if spec == nil or spec.isLocked then
        return
    end

    if not hasPhysicsAuthority(self) then
        return
    end

    pcall(setRigidBodyType, self.rootNode, RigidBodyType.KINEMATIC)
    spec.isLocked = true
end

function GroundLockOnFold:onUpdate(dt, isActiveForInput, isActiveForInputIgnoreSelection, isSelected)
    local spec = self.spec_groundLockOnFold
    if spec == nil then
        return
    end

    spec.lastCheckMs = spec.lastCheckMs + dt
    if spec.lastCheckMs < 150 then
        return
    end
    spec.lastCheckMs = 0

    local shouldLock = false
    if self.getIsUnfolded ~= nil then
        shouldLock = self:getIsUnfolded()
    elseif self.getFoldAnimTime ~= nil then
        shouldLock = self:getFoldAnimTime() > 0.95
    end

    if shouldLock and not getIsMoving(self) then
        setBodyKinematic(self)
    else
        setBodyDynamic(self)
    end
end

function GroundLockOnFold:onDelete()
    setBodyDynamic(self)
end
