--
-- ExtendedSowingMachine
--
-- @author  Stefan Maurus
-- @date    14/10/2020
--
-- Copyright (C) GIANTS Software GmbH, Confidential, All Rights Reserved.

---Specialization to track seed usage
-- @category Specializations
ExtendedSowingMachine = {}

ExtendedSowingMachine.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 ExtendedSowingMachine.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(SowingMachine, specializations) and SpecializationUtil.hasSpecialization(PrecisionFarmingStatistic, specializations)
end

function ExtendedSowingMachine.registerFunctions(vehicleType)
end

function ExtendedSowingMachine.registerOverwrittenFunctions(vehicleType)
end

function ExtendedSowingMachine.registerEventListeners(vehicleType)
    SpecializationUtil.registerEventListener(vehicleType, "onEndWorkAreaProcessing", ExtendedSowingMachine)
end

---
-- @includeCode
function ExtendedSowingMachine:onEndWorkAreaProcessing(dt, hasProcessed)
    local spec = self.spec_sowingMachine
    if self.isServer then
        if spec.workAreaParameters.lastChangedArea > 0 then
            local fruitDesc = g_fruitTypeManager:getFruitTypeByIndex(spec.workAreaParameters.seedsFruitType)
            local lastHa = MathUtil.areaToHa(spec.workAreaParameters.lastChangedArea, g_currentMission:getFruitPixelsToSqm())
            local usage = fruitDesc.seedUsagePerSqm * lastHa * 10000

            local damage = self:getVehicleDamage()
            if damage > 0 then
                usage = usage * (1 + damage * SowingMachine.DAMAGED_USAGE_INCREASE)
            end

            local farmlandStatistics, isOnField, farmlandId = self:getPAStatisticInfo()
            if isOnField then
                if farmlandStatistics ~= nil then
                    if farmlandId ~= nil then
                        farmlandStatistics:updateStatistic(farmlandId, "usedSeeds", usage)
                        farmlandStatistics:updateStatistic(farmlandId, "usedSeedsRegular", usage)
                    end
                end
            end
        end
    end
end
