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


FarmlandStatistic = {}

local FarmlandStatistic_mt = Class(FarmlandStatistic)

---
-- @includeCode
function FarmlandStatistic.new(farmlandId, customMt)
    local self = setmetatable({}, customMt or FarmlandStatistic_mt)

    self.farmlandId = farmlandId
    self.hasChanged = false

    self.periodCounter = FarmlandStatisticCounter.new()
    self.totalCounter = FarmlandStatisticCounter.new()

    return self
end

---
-- @includeCode
function FarmlandStatistic:loadFromItemsXML(xmlFile, key)
    if getXMLInt(xmlFile, key .. "#farmlandId") == self.farmlandId then
        self.periodCounter:loadFromItemsXML(xmlFile, key .. ".periodCounter")
        self.totalCounter:loadFromItemsXML(xmlFile, key .. ".totalCounter")
    else
        g_logManager:warning("Failed to load FarmlandStatistic from items xml (%s)", key)
    end
end

---
-- @includeCode
function FarmlandStatistic:saveToXMLFile(xmlFile, key, usedModNames)
    setXMLInt(xmlFile, key .. "#farmlandId", self.farmlandId)
    self.periodCounter:saveToXMLFile(xmlFile, key .. ".periodCounter", usedModNames)
    self.totalCounter:saveToXMLFile(xmlFile, key .. ".totalCounter", usedModNames)
end

---Called on client side on join
-- @param integer streamId streamId
-- @param integer connection connection
-- @includeCode
function FarmlandStatistic:onReadStream(streamId, connection)
    self.periodCounter:onReadStream(streamId, connection)
    self.totalCounter:onReadStream(streamId, connection)
end


---Called on server side on join
-- @param integer streamId streamId
-- @param integer connection connection
-- @includeCode
function FarmlandStatistic:onWriteStream(streamId, connection)
    self.periodCounter:onWriteStream(streamId, connection)
    self.totalCounter:onWriteStream(streamId, connection)
end

---
-- @includeCode
function FarmlandStatistic:reset(clearTotal)
    self.periodCounter:reset()

    if clearTotal then
        self.totalCounter:reset()
    end
end

---
-- @includeCode
function FarmlandStatistic:getValue(total, name)
    local counter = self.periodCounter
    if total then
        counter = self.totalCounter
    end

    if counter[name] ~= nil then
        return counter[name]
    end

    return 0
end

---
-- @includeCode
function FarmlandStatistic:updateStatistic(name, value)
    if self.periodCounter[name] ~= nil then
        self.periodCounter[name] = self.periodCounter[name] + value
    end

    if self.totalCounter[name] ~= nil then
        self.totalCounter[name] = self.totalCounter[name] + value
    end

    self.hasChanged = true
end
