-- scripts/AttachVisuals.lua
-- Mostra "attach" quando o container está ENGATADO como BigBag
-- e "detach" em qualquer outro caso (desanexado ou anexado via HookLift etc).

AttachVisuals = {}

local function setNodeSafeVisible(node, visible)
    if node ~= nil and node ~= 0 then
        setVisibility(node, visible)
    end
end

local function showAttached(spec, show)
    setNodeSafeVisible(spec.attachNode, show)
    setNodeSafeVisible(spec.detachNode, not show)
end

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

function AttachVisuals.initSpecialization()
    local schema = Vehicle.xmlSchema
    schema:register(XMLValueType.NODE_INDEX, "vehicle.attachVisuals#attachNode", "Nó visível quando ATTACHED", nil)
    schema:register(XMLValueType.NODE_INDEX, "vehicle.attachVisuals#detachNode", "Nó visível quando DETACHED", nil)
end

function AttachVisuals.registerEventListeners(vehicleType)
    SpecializationUtil.registerEventListener(vehicleType, "onLoad",       AttachVisuals)
    SpecializationUtil.registerEventListener(vehicleType, "onPostAttach", AttachVisuals)
    SpecializationUtil.registerEventListener(vehicleType, "onPreDetach",  AttachVisuals)
end

function AttachVisuals:onLoad(_)
    self.spec_attachVisuals = self.spec_attachVisuals or {}
    local spec = self.spec_attachVisuals

    spec.attachNode = self.xmlFile:getValue("vehicle.attachVisuals#attachNode", nil, self.components, self.i3dMappings)
    spec.detachNode = self.xmlFile:getValue("vehicle.attachVisuals#detachNode", nil, self.components, self.i3dMappings)

    -- Estado inicial: mostrar como DESANEXADO
    showAttached(spec, false)
end

-- Só anima quando o jointType usado é BIGBAG
local function isBigBagJoint(self, inputJointDescIndex)
    local aspec = self.spec_attachable
    if aspec == nil then return false end

    local inputJoints = aspec.inputAttacherJoints
    if inputJoints == nil then return false end

    local desc = inputJoints[inputJointDescIndex]
    if desc == nil then return false end

    -- Compara diretamente com a constante BIGBAG do jogo
    return desc.jointType == AttacherJoints.JOINTTYPE_BIGBAG
end

function AttachVisuals:onPostAttach(attacherVehicle, inputJointDescIndex, jointDescIndex, loadFromSavegame)
    local spec = self.spec_attachVisuals
    if spec == nil then return end

    -- Só mostra “attach” se for BigBag
    local bigBag = isBigBagJoint(self, inputJointDescIndex)
    showAttached(spec, bigBag)
end

function AttachVisuals:onPreDetach(implementIndex)
    local spec = self.spec_attachVisuals
    if spec == nil then return end
    -- Voltou a ficar “desanexado”
    showAttached(spec, false)
end
