--
-- Spec: LiveDelimber
-- Author: Bargon Mods
-- Email: bargonmods@gmail.com
-- Date: 24.01.2022
-- Version: 1.0.0.0
-- 
LiveDelimber = {}

function LiveDelimber.prerequisitesPresent(specializations)
    return true
end

function LiveDelimber.initSpecialization()
    local schema = Vehicle.xmlSchema
    schema:setXMLSpecializationType("LiveDelimber")

    schema:register(XMLValueType.NODE_INDEX, "vehicle.liveDelimber.delimbNode#node", "Delimb node")
    schema:register(XMLValueType.FLOAT, "vehicle.liveDelimber.delimbNode#sizeX", "Delimb size X", 0.3)
    schema:register(XMLValueType.FLOAT, "vehicle.liveDelimber.delimbNode#sizeY", "Delimb size Y", 2)
    schema:register(XMLValueType.FLOAT, "vehicle.liveDelimber.delimbNode#sizeZ", "Delimb size Z", 2)

    schema:setXMLSpecializationType()
end

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

function LiveDelimber:onLoad(savegame)
    self.spec_liveDelimber = {}

    local spec = self.spec_liveDelimber

    spec.delimbNode = self.xmlFile:getValue("vehicle.liveDelimber.delimbNode#node", nil, self.components,
        self.i3dMappings)
    spec.delimbSizeX = self.xmlFile:getValue("vehicle.liveDelimber.delimbNode#sizeX", 0.3)
    spec.delimbSizeY = self.xmlFile:getValue("vehicle.liveDelimber.delimbNode#sizeY", 2)
    spec.delimbSizeZ = self.xmlFile:getValue("vehicle.liveDelimber.delimbNode#sizeZ", 2)
end

function LiveDelimber:onUpdate(dt, isActiveForInput, isActiveForInputIgnoreSelection, isSelected)
    local spec = self.spec_liveDelimber

    if (spec.delimbNode ~= nil and spec.delimbSizeY ~= nil and spec.delimbSizeZ ~= nil) then
        local xD, yD, zD = getWorldTranslation(spec.delimbNode)
        local nxD, nyD, nzD = localDirectionToWorld(spec.delimbNode, 1, 0, 0)
        local yxD, yyD, yzD = localDirectionToWorld(spec.delimbNode, 0, 1, 0)
        findAndRemoveSplitShapeAttachments(xD, yD, zD, nxD, nyD, nzD, yxD, yyD, yzD, 0.7, spec.delimbSizeY,
            spec.delimbSizeZ)
    end
end
