-- motorsoundConfiguration.lua
-- sets an individual engine sound for engine configurations
--
-- Author Rival with help from bassaddict
-- 26.10.2016
--
-- convert FS19 Aluha74rus
MotorConfigSound = {};


function MotorConfigSound.prerequisitesPresent(specializations)
    return true;
end

function MotorConfigSound.initSpecialization()
end

function MotorConfigSound.registerOverwrittenFunctions(vehicleType)
end

function MotorConfigSound.registerFunctions(vehicleType)
end

function MotorConfigSound.registerEvents(vehicleType)
end

function MotorConfigSound:registerActionEventsPlayer()
end

function MotorConfigSound:registerActionEventsMenu()
end

function MotorConfigSound:onRegisterActionEvents(isSelected, isOnActiveVehicle)
end

function MotorConfigSound.registerEventListeners(vehicleType)
end

function MotorConfigSound:onLoad(savegame)
	local xmlFile = self.xmlFile;
	
	local key, motorId = ConfigurationUtil.getXMLConfigurationKey(self.xmlFile, self.configurations["motor"], "vehicle.motorized.motorConfigurations.motorConfiguration", "vehicle.motorized", "motortuningI3d");
    ObjectChangeUtil.updateObjectChanges(self.xmlFile, "vehicle.motorized.motorConfigurations.motorConfiguration", self.configurations["motor"], self.components, self)
    -- self.tuningMotorI3d = {}
    -- local i = 0
    -- while true do
        -- local key = string.format("vehicle.motorized.motorConfigurations.motorConfiguration(%d)", self.configurations["motor"]-i)
        -- if not hasXMLProperty(self.xmlFile, key) then
            -- break
        -- end
        -- local node = I3DUtil.indexToObject(self.components, getXMLString(self.xmlFile, key .. ".tuningMotor#node"), self.i3dMappings)
        -- if node ~= nil then
            -- local tuningMotorXmlFilename = getXMLString(self.xmlFile, key .. ".tuningMotor#filename")
            -- if tuningMotorXmlFilename ~= nil then
                -- tuningMotorXmlFilename = Utils.getFilename(tuningMotorXmlFilename, self.baseDirectory)
                -- local tuningMotorXmlFile = loadXMLFile("tuningI3dXML", tuningMotorXmlFilename)
                -- if tuningMotorXmlFile ~= nil and tuningMotorXmlFile ~= 0 then
                    -- local i3dFilename = getXMLString(tuningMotorXmlFile, "I3dDetal.filename")
                    -- if i3dFilename ~= nil then
                        -- local i3dNode = g_i3DManager:loadSharedI3DFile(i3dFilename, self.baseDirectory, false, false, false)
                        -- if i3dNode ~= nil and i3dNode ~= 0 then
                            -- local rootNode = I3DUtil.indexToObject(i3dNode, getXMLString(tuningMotorXmlFile, "I3dDetal.MotorDetal#node"))
                            -- if rootNode ~= nil then
                                -- link(node, rootNode)
                                -- setTranslation(rootNode, 0,0,0)
                                -- local tuningMotor = {}
                                -- tuningMotor.filename = i3dFilename
                                -- tuningMotor.rootNode = rootNode
                                -- table.insert(self.tuningMotorI3d, tuningMotor)
                            -- end
                            -- delete(i3dNode)
                        -- end
                    -- end
                    -- delete(tuningMotorXmlFile)
                -- end
            -- end
        -- end
        -- i = i + 1
    -- end
    local spec = self.spec_motorized
    XMLUtil.checkDeprecatedXMLElements(self.xmlFile, self.configFileName, "vehicle.turnedOnRotationNodes.turnedOnRotationNode#type", "vehicle.motor.animationNodes.animationNode", "motor") --FS17 to FS19
    XMLUtil.checkDeprecatedXMLElements(self.xmlFile, self.configFileName, "vehicle.differentialConfigurations", "vehicle.motorized.differentialConfigurations") --FS17 to FS19
    XMLUtil.checkDeprecatedXMLElements(self.xmlFile, self.configFileName, "vehicle.motorConfigurations", "vehicle.motorized.motorConfigurations") --FS17 to FS19
    XMLUtil.checkDeprecatedXMLElements(self.xmlFile, self.configFileName, "vehicle.fuelCapacity", "vehicle.fillUnit") --FS17 to FS19
    XMLUtil.checkDeprecatedXMLElements(self.xmlFile, self.configFileName, "vehicle.maximalAirConsumptionPerFullStop", "vehicle.motorized.consumerConfigurations.consumerConfiguration.consumer(with fill type 'air')#usage (is now in usage per second at full brake power)") --FS17 to FS19
    XMLUtil.checkDeprecatedXMLElements(self.xmlFile, self.configFileName, "vehicle.indoorHud.rpm", "vehicle.motorized.dashboards.dashboard with valueType 'rpm'") --FS17 to FS19
    XMLUtil.checkDeprecatedXMLElements(self.xmlFile, self.configFileName, "vehicle.indoorHud.speed", "vehicle.motorized.dashboards.dashboard with valueType 'speed'") --FS17 to FS19
    XMLUtil.checkDeprecatedXMLElements(self.xmlFile, self.configFileName, "vehicle.indoorHud.fuelUsage", "vehicle.motorized.dashboards.dashboard with valueType 'fuelUsage'") --FS17 to FS19
    XMLUtil.checkDeprecatedXMLElements(self.xmlFile, self.configFileName, "vehicle.indoorHud.fuel", "fillUnit.dashboard with valueType 'fillLevel'") --FS17 to FS19
    spec.motorizedNode = nil
    for _, component in pairs(self.components) do
        if component.motorized then
            spec.motorizedNode = component.node
            break
        end
    end
    self:loadDifferentials(self.xmlFile, self.differentialIndex)
    self:loadMotor(self.xmlFile, self.configurations["motor"])
    self:loadSounds(self.xmlFile, self.configurations["motor"])
    self:loadConsumerConfiguration(self.xmlFile, spec.consumerConfigurationIndex)
    if self.isClient then
        self:loadExhaustEffects(self.xmlFile)
    end
    spec.stopMotorOnLeave = true
    spec.motorStartDuration = 0
    if spec.samples ~= nil and spec.samples.motorStart ~= nil then
        spec.motorStartDuration = spec.samples.motorStart.duration
    end
    spec.motorStartDuration = Utils.getNoNil(Utils.getNoNil(getXMLFloat(self.xmlFile, "vehicle.motorized.motorStartDuration"), spec.motorStartDuration), 0)
    spec.consumersEmptyWarning = g_i18n:getText(Utils.getNoNil(getXMLString(self.xmlFile, "vehicle.motorized#consumersEmptyWarning"), "warning_motorFuelEmpty"), self.customEnvironment)
    spec.turnOnText = g_i18n:getText(Utils.getNoNil(getXMLString(self.xmlFile, "vehicle.motorized#turnOnText"), "action_startMotor"), self.customEnvironment)
    spec.turnOffText = g_i18n:getText(Utils.getNoNil(getXMLString(self.xmlFile, "vehicle.motorized#turnOffText"), "action_stopMotor"), self.customEnvironment)
    spec.speedDisplayScale = 1
    spec.motorStartTime = 0
    spec.lastRoundPerMinute = 0
    spec.actualLoadPercentage = 0
    spec.smoothedLoadPercentage = 0
    spec.maxDecelerationDuringBrake = 0
    spec.showTurnOnMotorWarning = 0
    spec.isMotorStarted = false
    spec.motorStopTimerDuration = g_gameSettings:getValue("motorStopTimerDuration")
    spec.motorStopTimer = spec.motorStopTimerDuration
    spec.motorTemperature = {}
    spec.motorTemperature.value = 20
    spec.motorTemperature.valueSend = 20
    spec.motorTemperature.valueMax = 120
    spec.motorTemperature.valueMin = 20
    spec.motorTemperature.heatingPerMS = 1.5 / 1000                                                    -- delta °C per ms, at full load
    spec.motorTemperature.coolingByWindPerMS = 1.00 / 1000
    spec.motorFan = {}
    spec.motorFan.enabled = false
    spec.motorFan.enableTemperature = 95
    spec.motorFan.disableTemperature = 85
    spec.motorFan.coolingPerMS = 3.0 / 1000
    spec.lastFuelUsage = 0
    spec.lastFuelUsageDisplay = 0
    spec.lastFuelUsageDisplayTime = 0
    spec.fuelUsageBuffer = ValueBuffer:new(250)
    spec.lastDefUsage = 0
    spec.lastAirUsage = 0
    spec.lastVehicleDamage = 0
    if self.loadDashboardsFromXML ~= nil then
        self:loadDashboardsFromXML(self.xmlFile, "vehicle.motorized.dashboards", {valueTypeToLoad = "rpm",
                                                                                  valueObject = spec.motor,
                                                                                  valueFunc = "getEqualizedMotorRpm",
                                                                                  minFunc = 0,
                                                                                  maxFunc = "getMaxRpm"})
        self:loadDashboardsFromXML(self.xmlFile, "vehicle.motorized.dashboards", {valueTypeToLoad = "speed",
                                                                                  valueObject = self,
                                                                                  valueFunc = "getLastSpeed",
                                                                                  minFunc = 0,
                                                                                  maxFunc = self:getMotor():getMaximumForwardSpeed()*3.6})
        self:loadDashboardsFromXML(self.xmlFile, "vehicle.motorized.dashboards", {valueTypeToLoad = "speedDir",
                                                                                  valueObject = self,
                                                                                  valueFunc = Motorized.getDashboardSpeedDir,
                                                                                  minFunc = -self:getMotor():getMaximumBackwardSpeed()*3.6,
                                                                                  maxFunc = self:getMotor():getMaximumForwardSpeed()*3.6,
                                                                                  centerFunc = 0})
        self:loadDashboardsFromXML(self.xmlFile, "vehicle.motorized.dashboards", {valueTypeToLoad = "fuelUsage",
                                                                                  valueObject = spec,
                                                                                  valueFunc = "lastFuelUsageDisplay"})
        self:loadDashboardsFromXML(self.xmlFile, "vehicle.motorized.dashboards", {valueTypeToLoad = "motorTemperature",
                                                                                  valueObject = spec.motorTemperature,
                                                                                  valueFunc = "value",
                                                                                  minFunc = "valueMin",
                                                                                  maxFunc = "valueMax"})
        self:loadDashboardsFromXML(self.xmlFile, "vehicle.motorized.dashboards", {valueTypeToLoad = "motorTemperatureWarning",
                                                                                  valueObject = spec.motorTemperature,
                                                                                  valueFunc = "value",
                                                                                  additionalAttributesFunc = Dashboard.warningAttributes,
                                                                                  stateFunc = Dashboard.warningState})
    end
    spec.animationNodes = g_animationManager:loadAnimations(self.xmlFile, "vehicle.motorized.animationNodes", self.components, self, self.i3dMappings)
    spec.dirtyFlag = self:getNextDirtyFlag()
end
Motorized.onLoad = Utils.overwrittenFunction(Motorized.onLoad, MotorConfigSound.onLoad);
function MotorConfigSound:onUpdate(dt)
end
function MotorConfigSound:onUpdateTick(dt)
end
function MotorConfigSound:onDelete()
end
function MotorConfigSound:loadSounds(xmlFile, motorId)
    if self.isClient then
		local xmlFile = self.xmlFile;
		local key, motorId = ConfigurationUtil.getXMLConfigurationKey(xmlFile, self.configurations["motor"], "vehicle.motorized.motorConfigurations.motorConfiguration", "vehicle.motorized", "motorsound");
        local spec = self.spec_motorized
		
    if key ~= nil and hasXMLProperty(xmlFile, key..".sounds(0)") then -- using default motor configuration
        baseString = key..".sounds"
		
        spec.samples = {}
        spec.samples.motorStart   = g_soundManager:loadSampleFromXML(xmlFile, baseString, "motorStart", self.baseDirectory, self.components, 1, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.motorStop    = g_soundManager:loadSampleFromXML(xmlFile, baseString, "motorStop", self.baseDirectory, self.components, 1, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.gearbox      = g_soundManager:loadSampleFromXML(xmlFile, baseString, "gearbox", self.baseDirectory, self.components, 0, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.retarder     = g_soundManager:loadSampleFromXML(xmlFile, baseString, "retarder", self.baseDirectory, self.components, 0, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.motorSamples = {}
        local i = 0
        while true do
            local sample = g_soundManager:loadSampleFromXML(xmlFile, baseString, string.format("motor(%d)", i), self.baseDirectory, self.components, 0, AudioGroup.VEHICLE, self.i3dMappings, self)
            if sample == nil then
                break
            end
            table.insert(spec.motorSamples, sample)
            i = i + 1
        end
        spec.samples.airCompressorStart   = g_soundManager:loadSampleFromXML(xmlFile, baseString, "airCompressorStart", self.baseDirectory, self.components, 1, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.airCompressorStop    = g_soundManager:loadSampleFromXML(xmlFile, baseString, "airCompressorStop", self.baseDirectory, self.components, 1, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.airCompressorRun     = g_soundManager:loadSampleFromXML(xmlFile, baseString, "airCompressorRun", self.baseDirectory, self.components, 0, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.compressedAir    = g_soundManager:loadSampleFromXML(xmlFile, baseString, "compressedAir", self.baseDirectory, self.components, 1, AudioGroup.VEHICLE, self.i3dMappings, self)
        if spec.samples.compressedAir ~= nil then
            spec.samples.compressedAir.brakeTime = 0
            spec.samples.compressedAir.lastBrakeTime = 0
        end
        spec.samples.airRelease       = g_soundManager:loadSampleFromXML(xmlFile, baseString, "airRelease", self.baseDirectory, self.components, 1, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.reverseDrive     = g_soundManager:loadSampleFromXML(xmlFile, baseString, "reverseDrive", self.baseDirectory, self.components, 0, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.reverseDriveThreshold    = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorized.reverseDriveSound#threshold"), 4)
        spec.brakeCompressor = {}
        spec.brakeCompressor.capacity = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorized.brakeCompressor#capacity"), 6)
        spec.brakeCompressor.refillFilllevel = math.min(spec.brakeCompressor.capacity, Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorized.brakeCompressor#refillFillLevel"), spec.brakeCompressor.capacity/2))
        spec.brakeCompressor.fillSpeed = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorized.brakeCompressor#fillSpeed"), 0.6) / 1000
        spec.brakeCompressor.fillLevel = 0
        spec.brakeCompressor.doFill = true
        spec.isBrakeSamplePlaying = false
        spec.samples.brake     = g_soundManager:loadSampleFromXML(xmlFile, baseString, "brake", self.baseDirectory, self.components, 0, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.compressionSoundTime = 0
    else
        baseString = "vehicle.motorized.sounds"
		
        spec.samples = {}
        spec.samples.motorStart   = g_soundManager:loadSampleFromXML(xmlFile, baseString, "motorStart", self.baseDirectory, self.components, 1, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.motorStop    = g_soundManager:loadSampleFromXML(xmlFile, baseString, "motorStop", self.baseDirectory, self.components, 1, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.gearbox      = g_soundManager:loadSampleFromXML(xmlFile, baseString, "gearbox", self.baseDirectory, self.components, 0, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.retarder     = g_soundManager:loadSampleFromXML(xmlFile, baseString, "retarder", self.baseDirectory, self.components, 0, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.motorSamples = {}
        local i = 0
        while true do
            local sample = g_soundManager:loadSampleFromXML(xmlFile, baseString, string.format("motor(%d)", i), self.baseDirectory, self.components, 0, AudioGroup.VEHICLE, self.i3dMappings, self)
            if sample == nil then
                break
            end
            table.insert(spec.motorSamples, sample)
            i = i + 1
        end
        spec.samples.airCompressorStart   = g_soundManager:loadSampleFromXML(xmlFile, baseString, "airCompressorStart", self.baseDirectory, self.components, 1, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.airCompressorStop    = g_soundManager:loadSampleFromXML(xmlFile, baseString, "airCompressorStop", self.baseDirectory, self.components, 1, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.airCompressorRun     = g_soundManager:loadSampleFromXML(xmlFile, baseString, "airCompressorRun", self.baseDirectory, self.components, 0, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.compressedAir    = g_soundManager:loadSampleFromXML(xmlFile, baseString, "compressedAir", self.baseDirectory, self.components, 1, AudioGroup.VEHICLE, self.i3dMappings, self)
        if spec.samples.compressedAir ~= nil then
            spec.samples.compressedAir.brakeTime = 0
            spec.samples.compressedAir.lastBrakeTime = 0
        end
        spec.samples.airRelease       = g_soundManager:loadSampleFromXML(xmlFile, baseString, "airRelease", self.baseDirectory, self.components, 1, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.samples.reverseDrive     = g_soundManager:loadSampleFromXML(xmlFile, baseString, "reverseDrive", self.baseDirectory, self.components, 0, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.reverseDriveThreshold    = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorized.reverseDriveSound#threshold"), 4)
        spec.brakeCompressor = {}
        spec.brakeCompressor.capacity = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorized.brakeCompressor#capacity"), 6)
        spec.brakeCompressor.refillFilllevel = math.min(spec.brakeCompressor.capacity, Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorized.brakeCompressor#refillFillLevel"), spec.brakeCompressor.capacity/2))
        spec.brakeCompressor.fillSpeed = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.motorized.brakeCompressor#fillSpeed"), 0.6) / 1000
        spec.brakeCompressor.fillLevel = 0
        spec.brakeCompressor.doFill = true
        spec.isBrakeSamplePlaying = false
        spec.samples.brake     = g_soundManager:loadSampleFromXML(xmlFile, baseString, "brake", self.baseDirectory, self.components, 0, AudioGroup.VEHICLE, self.i3dMappings, self)
        spec.compressionSoundTime = 0
    end
    end
end
Motorized.loadSounds = Utils.overwrittenFunction(Motorized.loadSounds, MotorConfigSound.loadSounds);