-- Copyright ©2024-2025 by Todd Hundersmarck (ThundR) 
-- All Rights Reserved

--[[

Unauthorized use and/or distribution of this work entitles myself, the author, to unlimited free and unrestricted use, access, and distribution of any works related to the unauthorized user and/or distributor.

--]]

local THNitrogenMap = {}
local THNitrogenMap_mt = Class(THNitrogenMap)
THNitrogenMap.DATA_KEY = tostring(THNitrogenMap)
local function getCustomData(parent)
    return THUtils.getDataTable(parent, THNitrogenMap.DATA_KEY)
end
THNitrogenMap.getCustomData = getCustomData
THSprayTypes.NitrogenMap = THNitrogenMap
local function initScript()
    local pfData = g_thPFConfig.precisionFarming
    if pfData.isFound then
        local pfModEnv = pfData.mod.environment
        local NitrogenMap = pfModEnv.NitrogenMap
        THUtils.overwriteFunction(NitrogenMap, "loadFromXML", false, false, nil, THNitrogenMap.gOverwrite_loadFromXML)
    end
end
function THNitrogenMap.new(parent, customMt)
    customMt = customMt or THNitrogenMap_mt
    if THUtils.argIsValid(type(parent) == THValueType.TABLE, "parent", parent)
        and THUtils.argIsValid(type(customMt) == THValueType.TABLE, "customMt", customMt)
    then
        local self = getCustomData(parent)
        if self == nil then
            self = THUtils.createDataTable(parent, THNitrogenMap.DATA_KEY, customMt)
        end
        return self
    end
end
function THNitrogenMap.gOverwrite_loadFromXML(superFunc, parent, xmlFile, xmlKey, baseDirectory, customEnv, ...)
    local pfData = g_thPFConfig.precisionFarming
    local areValuesAdded = false
    if pfData.isFound then
        THUtils.pcall(function()
            local self = getCustomData(parent)
            local wrappedXML = THUtils.wrapXMLFile(xmlFile)
            if self == nil then
                self = THNitrogenMap.new(parent)
            end
            if self ~= nil and wrappedXML ~= nil then
                local xmlBaseKey = xmlKey .. ".nitrogenMap"
                local userOnLoadValues = g_thSprayTypes.userOnLoadValues.modSprayTypes
                local appRateSprayTypes = {}
                local fertUsageSprayTypes = {}
                local nextAppRateXMLIndex = 0
                local nextFertUsageXMLIndex = 0
                wrappedXML:iterate(xmlBaseKey .. ".applicationRates.applicationRate", function(_, pAppRateKey)
                    local fillTypeName = wrappedXML:getString(pAppRateKey .. "#fillType")
                    if fillTypeName ~= nil and fillTypeName ~= "" then
                        appRateSprayTypes[fillTypeName:upper()] = true
                    end
                    nextAppRateXMLIndex = nextAppRateXMLIndex + 1
                end)
                wrappedXML:iterate(xmlBaseKey .. ".fertilizerUsage.nAmount", function(_, pFertUsageKey)
                    local fillTypeName = wrappedXML:getString(pFertUsageKey .. "#fillType")
                    if fillTypeName ~= nil and fillTypeName ~= "" then
                        fertUsageSprayTypes[fillTypeName:upper()] = true
                    end
                    nextFertUsageXMLIndex = nextFertUsageXMLIndex + 1
                end)
                for _, userData in pairs(userOnLoadValues) do
                    if appRateSprayTypes[userData.name] == nil then
                        local appRateKey = string.format("%s.applicationRates.applicationRate(%d)", xmlBaseKey, nextAppRateXMLIndex)
                        local appRateData = userData.pfApplicationRate
                        if appRateData ~= nil then
                            wrappedXML:setString(appRateKey .. "#fillType", userData.name)
                            if appRateData.adjustToFruit ~= nil then
                                wrappedXML:setBool(appRateKey .. "#autoAdjustToFruit", appRateData.adjustToFruit)
                            end
                            if appRateData.regularRate ~= nil then
                                wrappedXML:setFloat(appRateKey .. "#regularRate", appRateData.regularRate)
                            end
                            local soilRateValues = appRateData.soilRates
                            local soilRateXMLIndex = 0
                            if soilRateValues ~= nil then
                                for _, soilRateData in ipairs(soilRateValues) do
                                    local soilRateKey = string.format("%s.soil(%d)", appRateKey, soilRateXMLIndex)
                                    if soilRateData.soilTypeIndex ~= nil and soilRateData.soilRate ~= nil then
                                        wrappedXML:setInt(soilRateKey .. "#soilTypeIndex", soilRateData.soilTypeIndex)
                                        wrappedXML:setFloat(soilRateKey .. "#rate", soilRateData.soilRate)
                                        soilRateXMLIndex = soilRateXMLIndex + 1
                                    end
                                end
                            end
                            nextAppRateXMLIndex = nextAppRateXMLIndex + 1
                            THUtils.displayMsg("Injecting %q application rate", userData.name)
                            areValuesAdded = true
                        end
                    end
                    if fertUsageSprayTypes[userData.name] == nil then
                        local fertUsageKey = string.format("%s.fertilizerUsage.nAmount(%d)", xmlBaseKey, nextFertUsageXMLIndex)
                        local fertUsageData = userData.pfFertilizerUsage
                        if fertUsageData ~= nil then
                            wrappedXML:setString(fertUsageKey .. "#fillType", userData.name)
                            if fertUsageData.nAmount ~= nil then
                                wrappedXML:setFloat(fertUsageKey .. "#amount", fertUsageData.nAmount)
                            end
                            nextFertUsageXMLIndex = nextFertUsageXMLIndex + 1
                            THUtils.displayMsg("Injecting %q fertilizer usage", userData.name)
                            areValuesAdded = true
                        end
                    end
                end
            end
        end)
    end
    local function appendFunc(...)
        if areValuesAdded then
            THUtils.pcall(function()
                if THUtils.getIsDebugEnabled() then
                    THUtils.displayMsg("")
                    THUtils.displayMsg("PF nitrogenMap application rates:")
                    THUtils.printTableValues(parent.applicationRates, 5)
                    THUtils.displayMsg("PF nitrogenMap fertilizer usages:")
                    THUtils.printTableValues(parent.fertilizerUsage, 5)
                end
            end)
        end
        return ...
    end
    return appendFunc(superFunc(parent, xmlFile, xmlKey, baseDirectory, customEnv, ...))
end
THUtils.pcall(initScript)