-- scripts/CustomRopes.lua

CustomRopes = {}
CustomRopes.ModDirectory = g_currentModDirectory

function CustomRopes.initSpecialization()
end

function CustomRopes.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Attachable, specializations)
end

function CustomRopes.registerEventListeners(vehicleType)
    SpecializationUtil.registerEventListener(vehicleType, "onLoad",        CustomRopes)
    SpecializationUtil.registerEventListener(vehicleType, "onPreDetach",    CustomRopes)
	SpecializationUtil.registerEventListener(vehicleType, "onPreAttach",    CustomRopes)
end

function CustomRopes:onLoad(savegame)
    self.ropeNodes = {}

    for i = 1, 8 do
        local key = string.format("vehicle.customRopes.rope%02d#node", i)
        local path = self.xmlFile:getString(key) or ""
        local node = (path ~= "" and I3DUtil.indexToObject(self.components, path)) or nil

        if not node then
            Logging.xmlWarning(self.xmlFile, "CustomRopes: Rope node '%s' not found!", path)
        end
        table.insert(self.ropeNodes, {
            node   = node,
            isAttach = (i <= 4)
        })
    end

	for _, rope in ipairs(self.ropeNodes) do
        if rope.node then
            if rope.isAttach then
				setVisibility(rope.node, false)
			else 
				setVisibility(rope.node, true)
			end
        end
    end
end


function CustomRopes:onPreAttach(attacherVehicle, inputJointDescIndex, jointDescIndex, loadFromSavegame)
	for _, rope in ipairs(self.ropeNodes) do
        if rope.node then
			if rope.isAttach then
				setVisibility(rope.node, true)
			else 
				setVisibility(rope.node, false)
			end
        end
    end
end

function CustomRopes:onPreDetach(implementIndex)
	for _, rope in ipairs(self.ropeNodes) do
        if rope.node then
			if rope.isAttach then
				setVisibility(rope.node, false)
			else 
				setVisibility(rope.node, true)
			end
        end
    end
end

