--
-- ExtendedMotorized
--
-- @author  Stefan Maurus
-- @date  16/09/2020
--
-- Copyright (C) GIANTS Software GmbH, Confidential, All Rights Reserved.

---Specialization to track fuel usage when vehicle is on a field
-- @category Specializations
ExtendedMotorized = {}

ExtendedMotorized.MOD_NAME = g_currentModName

---Checks if all prerequisite specializations are loaded
-- @param table specializations specializations
-- @return boolean hasPrerequisite true if all prerequisite specializations are loaded
-- @includeCode
function ExtendedMotorized.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Motorized, specializations) and SpecializationUtil.hasSpecialization(PrecisionFarmingStatistic, specializations)
end

function ExtendedMotorized.registerFunctions(vehicleType)
end

function ExtendedMotorized.registerOverwrittenFunctions(vehicleType)
    SpecializationUtil.registerOverwrittenFunction(vehicleType, "updateConsumers", ExtendedMotorized.updateConsumers)
end

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

function ExtendedMotorized:onLoad(savegame)
    local specName = ExtendedMotorized.MOD_NAME .. ".extendedMotorized"
    self.spec_extendedMotorized = self["spec_" .. specName]
    local spec = self.spec_extendedMotorized

    if g_precisionFarming ~= nil then
        spec.farmlandStatistics = g_precisionFarming.farmlandStatistics
    end
end

---
-- @includeCode
function ExtendedMotorized:updateConsumers(superFunc, dt, accInput)
    local spec = self.spec_motorized

    local farmlandStatistics, isOnField, farmlandId = self:getPAStatisticInfo()
    local dieselFillUnit = nil
    local dieselStartFillLevel = 0

    if isOnField then
        for _,consumer in pairs(spec.consumers) do
            if consumer.permanentConsumption and consumer.usage > 0 then
                local fillUnit = self:getFillUnitByIndex(consumer.fillUnitIndex)
                if fillUnit ~= nil and fillUnit.lastValidFillType == FillType.DIESEL then
                    dieselFillUnit = fillUnit
                    dieselStartFillLevel = dieselFillUnit.fillLevel
                end
            end
        end
    end

    superFunc(self, dt, accInput)

    if isOnField and dieselFillUnit ~= nil then
        local dieselUsed = math.max(dieselStartFillLevel - dieselFillUnit.fillLevel, 0)
        if dieselUsed > 0 then
            if farmlandStatistics ~= nil then
                if farmlandId ~= nil then
                    farmlandStatistics:updateStatistic(farmlandId, "usedFuel", dieselUsed)
                end
            end
        end
    end
end
