--- Specialization for attaching the EX400 backspar to the yarder
YarderBacksparAttacher = {}
YarderBacksparAttacher.MOD_NAME = g_currentModName
YarderBacksparAttacher.SPEC_NAME = "yarderBacksparAttacher"

function YarderBacksparAttacher.prerequisitesPresent(specializations)
    return true
end

function YarderBacksparAttacher.registerFunctions(vehicleType)
    SpecializationUtil.registerFunction(vehicleType, "attachBackspar", YarderBacksparAttacher.attachBackspar)
    SpecializationUtil.registerFunction(vehicleType, "detachBackspar", YarderBacksparAttacher.detachBackspar)
end

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

function YarderBacksparAttacher:onLoad(savegame)
    self.spec_yarderBacksparAttacher = {}
    local spec = self.spec_yarderBacksparAttacher

    spec.isBacksparAttached = false
    spec.backsparObject = nil
end

function YarderBacksparAttacher:onUpdate(dt)
    local spec = self.spec_yarderBacksparAttacher

    if not spec.isBacksparAttached then
        -- Check for nearby EX400 backspar
        local x, y, z = getWorldTranslation(self.rootNode)
        local radius = 5 -- Detection radius
        local nearbyVehicles = g_currentMission.nodeToObject

        for _, vehicle in pairs(nearbyVehicles) do
            if vehicle.typeName == "ex400" then
                local vx, vy, vz = getWorldTranslation(vehicle.rootNode)
                local distance = MathUtil.vector3Length(x - vx, y - vy, z - vz)

                if distance <= radius then
                    -- Attach the main rope to the backspar
                    self:attachMainRopeToBackspar(vehicle)
                    break
                end
            end
        end
    end
end

function YarderBacksparAttacher:attachMainRopeToBackspar(backsparObject)
    local spec = self.spec_yarderBacksparAttacher

    if not spec.isBacksparAttached then
        spec.isBacksparAttached = true
        spec.backsparObject = backsparObject

        -- Attach the main rope to the specified node
        local node = I3DUtil.indexToObject(backsparObject.rootNode, "0>6|0|0|3|9|2|0")
        if node ~= nil then
            -- Logic to connect the main rope to the node
            print("Main rope attached to backspar node successfully!")
        else
            print("Failed to find the main rope attachment node on the backspar.")
        end
    end
end

function YarderBacksparAttacher:detachBackspar()
    local spec = self.spec_yarderBacksparAttacher

    if spec.isBacksparAttached then
        spec.isBacksparAttached = false
        spec.backsparObject = nil

        -- Additional logic for detaching the backspar
        print("Backspar detached successfully!")
    end
end

return YarderBacksparAttacher