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

---Specialization to track vehicle wear costs
-- @category Specializations
ExtendedWearable = {}

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

function ExtendedWearable.registerFunctions(vehicleType)
end

function ExtendedWearable.registerOverwrittenFunctions(vehicleType)
end

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

function ExtendedWearable:onLoad(savegame)
    local specName = ExtendedWearable.MOD_NAME .. ".extendedWearable"
    self.spec_extendedWearable = self["spec_" .. specName]
    local spec = self.spec_extendedWearable

    spec.lastWearAmount = -1
end

---
-- @includeCode
function ExtendedWearable:onPostUpdateTick(dt, isActive, isActiveForInput, isSelected)
    local spec = self.spec_extendedWearable
    local specWear = self.spec_wearable

    local wearAmount = 0
    for i=1, #specWear.wearableNodes do
        wearAmount = wearAmount + specWear.wearableNodes[i].wearAmount
    end
    wearAmount = wearAmount / #specWear.wearableNodes

    if spec.lastWearAmount > 0 then
        local difference = wearAmount - spec.lastWearAmount
        if difference > 0 then
            local farmlandStatistics, isOnField, farmlandId = self:getPAStatisticInfo()
            if isOnField then
                if farmlandStatistics ~= nil then
                    if farmlandId ~= nil then
                        local repairCosts = self:getPrice() * difference / 100

                        farmlandStatistics:updateStatistic(farmlandId, "vehicleCosts", repairCosts)
                    end
                end
            end
        end
    end

    spec.lastWearAmount = wearAmount
end
