
--===============================================================
-- BASE GAME - ADD ANHYDROUS AS SPRAY TYPE
--===============================================================

local function addSprayType(sprayName, appRate, spraytypeName, groundType, baseType)

    if sprayName ~= nil and appRate ~= nil and spraytypeName ~= nil and groundType ~= nil and baseType ~= nil then
		-- print("SprayName: "..sprayName, "AppRate: "..appRate, "SprayType: "..spraytypeName, "Ground: "..groundType, "Base: "..tostring(baseType))
        if g_sprayTypeManager:addSprayType(sprayName, appRate, spraytypeName, groundType, baseType) then
			print("  INFO: Added Spraytype - "..sprayName)
        end
    end	
end
local function appendLoadMapData(self)

	print("  INFO: Registering New Spray Types")
    addSprayType("ANHYDROUS", 0.0081, "FERTILIZER", FieldSprayType.FERTILIZER, true)
	
end
SprayTypeManager.loadMapData = Utils.appendedFunction(SprayTypeManager.loadMapData, appendLoadMapData)

--===============================================================
-- PRECISION FARMING - ADD ANHYDROUS AS SPRAY TYPE
--===============================================================

local function injectPrecisionFarmingFunctions()

	if not _G['FS22_precisionFarming'] then
		return
	end
	
	print("  INFO: Injecting ANHYDROUS into Precision Farming")
	
	local function loadNitrogenMap(self, xmlFile, key, baseDirectory, configFileName, mapFilename)
	
		local nAmount = {
			fillTypeIndex = FillType.ANHYDROUS,
			amount = 0.82
		}
		table.insert(self.fertilizerUsage.nAmounts, nAmount)

		local applicationRate = {
			fillTypeIndex = FillType.ANHYDROUS,
			autoAdjustToFruit = true,
			regularRate = 150,
			ratesBySoilType = {}
		}
		table.insert(applicationRate.ratesBySoilType, {
			soilTypeIndex = 1,
			rate = 95 / self.amountPerState
		})
		table.insert(applicationRate.ratesBySoilType, {
			soilTypeIndex = 2,
			rate = 120 / self.amountPerState
		})
		table.insert(applicationRate.ratesBySoilType, {
			soilTypeIndex = 3,
			rate = 150 / self.amountPerState
		})
		table.insert(applicationRate.ratesBySoilType, {
			soilTypeIndex = 4,
			rate = 110 / self.amountPerState
		})
		table.insert(self.applicationRates, applicationRate)

	end

	local NitrogenMap = _G['FS22_precisionFarming'].NitrogenMap
	NitrogenMap.loadFromXML = Utils.appendedFunction(NitrogenMap.loadFromXML, loadNitrogenMap)


	local function newHUDExtension(self, superFunc, vehicle, uiScale, uiTextColor, uiTextSize)

		local HUDExtension = superFunc(self, vehicle, uiScale, uiTextColor, uiTextSize)
		local texts = HUDExtension.texts
		
		texts['headline_n_liquidFertilizer_ORIGINAL'] = HUDExtension.texts.headline_n_liquidFertilizer
		texts['headline_n_liquidFertilizer_ANHYDROUS'] = HUDExtension.texts.headline_n_liquidFertilizer:gsub("Liquid Fertilizer", "Anhydrous")
		
		return HUDExtension
	end

	local function drawHUDExtension(self, leftPosX, rightPosX, posY)

		if not self:canDraw() then
			return
		end

		local spec = self.vehicle.spec_extendedSprayer
		if self.validVehicle and self.realVehicle then
			if spec.isSlurryTanker or spec.isLiquidFertilizerSprayer then

				local sourceVehicle, sourceFillUnitIndex = self:getFillTypeSourceVehicle(self.realVehicle)
				if sourceVehicle:getFillUnitFillType(sourceFillUnitIndex) == FillType.ANHYDROUS and sourceVehicle:getFillUnitFillLevel(sourceFillUnitIndex) > 0 then
					-- print("ANHYDROUS")
					
					if spec.originalType == nil and spec.isSlurryTanker then
						spec.originalType = 'slurryTanker'
						spec.isSlurryTanker = false
						spec.isLiquidFertilizerSprayer = true
					end
					self.texts.headline_n_liquidFertilizer = self.texts.headline_n_liquidFertilizer_ANHYDROUS

				else
					-- print("NOT ANHYDROUS")

					if spec.originalType and spec.originalType == 'slurryTanker' then
						spec.originalType = nil
						spec.isSlurryTanker = true
						spec.isLiquidFertilizerSprayer = false
					end
					self.texts.headline_n_liquidFertilizer = self.texts.headline_n_liquidFertilizer_ORIGINAL
					
				end
			end
		end
		
	end

	local HUDExtension = _G['FS22_precisionFarming'].ExtendedSprayerHUDExtension
	HUDExtension.new = Utils.overwrittenFunction(HUDExtension.new, newHUDExtension)
	HUDExtension.draw = Utils.prependedFunction(HUDExtension.draw, drawHUDExtension)


	local function onEndWorkAreaProcessing(self, dt, hasProcessed)
		local spec = self.spec_extendedSprayer
		local specSprayer = self.spec_sprayer

		if self.isServer and specSprayer.workAreaParameters.isActive then
			local sprayVehicle = specSprayer.workAreaParameters.sprayVehicle
			local usage = specSprayer.workAreaParameters.usage
			local fillType = specSprayer.workAreaParameters.sprayFillType

			if (sprayVehicle ~= nil or self:getIsAIActive()) and self:getIsTurnedOn() then
				local usageRegular = spec.lastRegularUsage
				local farmlandStatistics, _, farmlandId = self:getPFStatisticInfo()

				if farmlandStatistics ~= nil and farmlandId ~= nil then
					if fillType == FillType.ANHYDROUS then
						farmlandStatistics:updateStatistic(farmlandId, "usedLiquidFertilizer", usage)
						farmlandStatistics:updateStatistic(farmlandId, "usedLiquidFertilizerRegular", usageRegular)
						--print(" usage " .. tostring(usage))
					end
				end
			end
		end
	end

	local function getCurrentSprayerMode(self, superFunc)
		local ExtendedSprayer = _G['FS22_precisionFarming'].ExtendedSprayer
		local sprayer, fillUnitIndex = ExtendedSprayer.getFillTypeSourceVehicle(self)
		local fillType = sprayer:getFillUnitLastValidFillType(fillUnitIndex)
		if fillType == FillType.ANHYDROUS then
			return false, true
		else
			return superFunc(self)
		end
	end

	local ExtendedSprayer = _G['FS22_precisionFarming'].ExtendedSprayer
	ExtendedSprayer.onEndWorkAreaProcessing = Utils.appendedFunction(ExtendedSprayer.onEndWorkAreaProcessing, onEndWorkAreaProcessing)
	ExtendedSprayer.getCurrentSprayerMode = Utils.overwrittenFunction(ExtendedSprayer.getCurrentSprayerMode, getCurrentSprayerMode)
	
	
	function loadFromItemsXML(self, xmlFile, key)

		print("key: ".. tostring(key) )
		print("statistics: ".. tostring(self.statisticsByFarmland) )
		-- DebugUtil.printTableRecursively(self.statisticsByFarmland, "--", 0, 1)
		
	end

	local FarmlandStatistics = _G['FS22_precisionFarming'].FarmlandStatistics
	FarmlandStatistics.loadFromItemsXML = Utils.appendedFunction(FarmlandStatistics.loadFromItemsXML, loadFromItemsXML)
	
end

local function prependFinalizeTypes(self)


    if self.rootElementName == 'vehicleTypes' then
        -- print("   FINALIZE VEHICLE TYPES ")
        if g_modIsLoaded['FS22_precisionFarming'] then
            print("  INFO: Precision Farming Loaded")
            injectPrecisionFarmingFunctions()
        end
    end
	
end
local oldFinalizeTypes = getmetatable(_G).__index.TypeManager.finalizeTypes
getmetatable(_G).__index.TypeManager.finalizeTypes = function(...) prependFinalizeTypes(...) return oldFinalizeTypes(...) end


local function appendLoadFillUnit(self, savegame)
	
	local isValidVehicle = {
	
		-- NOTE:  UNCOMMENT ANY OF THE ITEMS BELOW TO USE THEM WITH ANHYDROUS
		
		-- Slurry Tanks
		-- ['data/vehicles/farmtech/supercis800/supercis800.xml'] = true,
		-- ['data/vehicles/kotte/frc55/frc55.xml'] = true,
		-- ['data/vehicles/kotte/frc65/frc65.xml'] = true,
		-- ['data/vehicles/rudolfSchouten/vt130/vt130.xml'] = true,
		-- ['data/vehicles/farmtech/polycis1550/polycis1550.xml'] = true,
		-- ['data/vehicles/fliegl/pfw18000MaxxLinePlus/pfw18000MaxxLinePlus.xml'] = true,
		-- ['data/vehicles/briri/fieldMaster20/fieldMaster20.xml'] = true,
		-- ['data/vehicles/veenhuis/premiumIntegral20000/premiumIntegral20000.xml'] = true,
		-- ['data/vehicles/kotte/tsa/tsa.xml'] = true,
		-- ['data/vehicles/kotte/pq32000/pq32000.xml'] = true,
		-- ['data/vehicles/veenhuis/premiumIntegral30000/premiumIntegral30000.xml'] = true,

		-- Self-Propelled Slurry Tanks
		-- ['data/vehicles/vervaet/hydroTrikeXL/hydroTrikeXL.xml'] = true,
		-- ['data/vehicles/ploeger/at5104LNMS/at5104LNMS.xml'] = true,
	
		-- Slurry Spreaders
		-- ['data/vehicles/farmtech/variofex750/variofex750.xml'] = true,
		-- ['data/vehicles/brantner/ta12050/ta12050.xml'] = true,
		-- ['data/vehicles/briri/manureDirector14/manureDirector14.xml'] = true,
		-- ['data/vehicles/kuhn/slc141/slc141.xml'] = true,
		-- ['data/vehicles/hawe/dst16/dst16.xml'] = true,
		-- ['data/vehicles/samsonAgro/flex2023/flex2023.xml'] = true,
		-- ['data/vehicles/bergmann/tsw6240w/tsw6240w.xml'] = true,
		-- ['data/vehicles/samsonAgro/us235/us235.xml'] = true,
		-- ['data/vehicles/strautmann/ps3401/ps3401.xml'] = true,

		-- Slurry Sprayers
		-- ['data/vehicles/rudolfSchouten/sp6834/sp6834.xml'] = true,
		-- ['data/vehicles/bomech/tracPack/tracPack.xml'] = true,
		-- ['data/vehicles/bomech/multiProfi/multiProfi.xml'] = true,
		-- ['data/vehicles/bomech/multi4XL/multi4XL.xml'] = true,
		-- ['data/vehicles/hardi/mega1200L/mega1200L.xml'] = true,
		-- ['data/vehicles/hardi/mega1200L/mega1200LTank.xml'] = true,
		-- ['data/vehicles/hardi/navigator4000/navigator4000.xml'] = true,
		-- ['data/vehicles/hardi/commander4500DF/commander4500DF.xml'] = true,
		-- ['data/vehicles/hardi/aeon5200/aeon5200.xml'] = true,
		-- ['data/vehicles/berthoud/vantage4300/vantage4300.xml'] = true,
		['data/vehicles/samsonAgro/sbh4_36/sbh4_36.xml'] = true,
		
		['data/vehicles/zunhammer/ult18/ult18.xml'] = true,
		['data/vehicles/zunhammer/ult24/ult24.xml'] = true,
		['data/vehicles/samsonAgro/pgII35m/pgII35m.xml'] = true,
		
		--Referencing other installed mods you wish to enable to accept anhydrous
		--Ensure  all prior lines end with a comma, and the final line does not, as illustrated below.
		--[g_modsDirectory .. 'FS22_FertSubSoiler/B_B_LargeToolbar.xml'] = true,
		
		[g_modsDirectory .. 'FS22_JD_1775NT_2022/1775NT_2022.xml'] = true
		
		--If new mod references are added, each line must end with a comma(,) except for the last line
		
		
	}

	if isValidVehicle[self.configFileName]
	or self.typeName == 'fertilizingCultivator'
	or self.typeName == 'fillableImplement'
	then
		for _, fillUnit in ipairs(self.spec_fillUnit.fillUnits) do
			if fillUnit.supportedFillTypes[FillType.LIQUIDFERTILIZER]
			or fillUnit.supportedFillTypes[FillType.LIQUIDMANURE]
			then
				fillUnit.supportedFillTypes[FillType.ANHYDROUS] = true
			end
		end
	end

end
local oldLoadFillUnit = getmetatable(_G).__index.FillUnit.onLoad
getmetatable(_G).__index.FillUnit.onLoad = function(...) local res = oldLoadFillUnit(...) appendLoadFillUnit(...) return res end
