GreenhouseStorage = {}

local RainCoef = 0.001
local MeltCoef = 0.0001 -- to increase amount of water when snow is melting change this value

local WaterIndex

local modDir = g_currentModDirectory
local GreenhouseStorageManureXmlFile = modDir .. "xml/greenHouseGardenManure.xml"
local GreenhouseStorageFertilizierXmlFile = modDir .. "xml/greenHouseGardenFertilizer.xml"

function GreenhouseStorage:loadMap(savegame)
    for idx, fillType in pairs(g_fillTypeManager.indexToName) do
        if fillType == "WATER" then
            WaterIndex = idx
        end
    end
end

function GreenhouseStorage:update(dt)
    local currentWeather = g_currentMission.environment.weather.forecast:getCurrentWeather()
    local temperature = currentWeather.temperature
    local rainfallScale = g_currentMission.environment.weather.rainUpdater.rainfallScale
    local snowHeight = g_currentMission.environment.weather.snowHeight

    if g_currentMission.placeableSystem.placeables ~= nil then
        for _, placeable in pairs(g_currentMission.placeableSystem.placeables) do
            if placeable.configFileName == GreenhouseStorageManureXmlFile or placeable.configFileName ==
                GreenhouseStorageFertilizierXmlFile then

                local storage

                if placeable.spec_productionPoint ~= nil and placeable.spec_productionPoint.productionPoint.storage then
                    storage = placeable.spec_productionPoint.productionPoint.storage

                    if rainfallScale > 0 and storage:getFreeCapacity(WaterIndex) > 0 then
                        local amountWater = storage.fillLevels[WaterIndex]
                        amountWater = amountWater + RainCoef * rainfallScale * g_currentMission:getEffectiveTimeScale()
                        storage:setFillLevel(amountWater, WaterIndex)
                    end

                    if snowHeight >= 0.063 and temperature > 0 then
                        if storage:getFreeCapacity(WaterIndex) > 0 then
                            local amountWater = storage.fillLevels[WaterIndex]
                            amountWater = amountWater + MeltCoef * temperature * snowHeight *
                                              g_currentMission:getEffectiveTimeScale()
                            storage:setFillLevel(amountWater, WaterIndex)
                        end
                    end
                end
            end
        end
    end
end

addModEventListener(GreenhouseStorage)
