----------------------------------------------------------------------------------------------------
-- SilageDistributorParticles
----------------------------------------------------------------------------------------------------
-- Purpose: Particles for the silage distributor
--
-- Based on: particle script from rafftnix.
--
-- Copyright (c) Wopster, 2021
--
-- FARMING SIMULATOR 22 (c)IFKO [NATOR]
----------------------------------------------------------------------------------------------------

---@class SilageDistributorParticles
SilageDistributorParticles = {};
SilageDistributorParticles.MOD_NAME = g_currentModName;

function SilageDistributorParticles.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(TurnOnVehicle, specializations);
end;

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

function SilageDistributorParticles:onLoad(savegame)
    self.spec_silageDistributorParticles = self[("spec_%s.silageDistributorParticles"):format(SilageDistributorParticles.MOD_NAME)];

    local spec = self.spec_silageDistributorParticles;
    local xmlFile = loadXMLFile("vehicle", self.xmlFile.filename);

    local groundReferenceNodeIndex = getXMLInt(xmlFile, "vehicle.distributor.groundReference#index");

    if groundReferenceNodeIndex == nil then
        g_logManager:xmlWarning(self.configFileName, "Missing groundReference 'distributor.groundReference#index' for distributor.");
    end;

    spec.groundReferenceNode = self:getGroundReferenceNodeFromIndex(groundReferenceNodeIndex);
    spec.distributorParticleSystem = {};

    ParticleUtil.loadParticleSystem(xmlFile, spec.distributorParticleSystem, "vehicle.distributor.particleSystem", self.components, false, nil, self.baseDirectory);

    delete(xmlFile);
end;

function SilageDistributorParticles:onDelete()
    local spec = self.spec_silageDistributorParticles;

    ParticleUtil.deleteParticleSystem(spec.distributorParticleSystem);
end;

function SilageDistributorParticles:onUpdate(dt)
    if not self.isClient then
        return;
    end;

    local spec = self.spec_silageDistributorParticles;
    local particlesActive = false;

    if spec.groundReferenceNode ~= nil then
        particlesActive = self:getIsTurnedOn() and self:getIsGroundReferenceNodeActive(spec.groundReferenceNode)
    end;

    ParticleUtil.setEmittingState(spec.distributorParticleSystem, particlesActive);
end;