-- by modelleicher
-- V 1.1 - Error without precision farming fixed

grasslandSubsoiler = {};

function grasslandSubsoiler.prerequisitesPresent(specializations)
    return true;
end;

function grasslandSubsoiler.registerEventListeners(vehicleType)	
	g_materialManager:addMaterialType("grass_subsoiler")
end;

function grasslandSubsoiler.registerFunctions(vehicleType)
	SpecializationUtil.registerFunction(vehicleType, "processGrasslandSubsoilerArea", grasslandSubsoiler.processGrasslandSubsoilerArea)
end

function grasslandSubsoiler:processGrasslandSubsoilerArea(workArea, dt)
	local spec = self.spec_cultivator;
	
	local xs, _, zs = getWorldTranslation(workArea.start);
	local xw, _, zw = getWorldTranslation(workArea.width);
	local xh, _, zh = getWorldTranslation(workArea.height);	

	local sprayType = g_sprayTypeManager:getSprayTypeIndexByFillTypeIndex(g_fillTypeManager:getFillTypeIndexByName("fertilizer"))
	local changedArea, totalArea = 0, 0;
		
	if FS19_precisionFarming ~= nil and FS19_precisionFarming.g_precisionFarming ~= nil then
		-- call precision farming function if precicion farming is active
		changedArea = FS19_precisionFarming.g_precisionFarming.nitrogenMap:updateSprayArea(xs, zs, xw, zw, xh, zh, sprayType, sprayType, false, 1)

		if spec.isSubsoiler then
			FSDensityMapUtil.updateSubsoilerArea(xs, zs, xw, zw, xh, zh);
		end

		FSDensityMapUtil.eraseTireTrack(xs, zs, xw, zw, xh, zh);
	
		-- pf function does not automatically add ground type to spray type but uses it as mask so we need to add it manually
		local desc = g_sprayTypeManager:getSprayTypeByIndex(sprayType)
		if desc ~= nil then
			FSDensityMapUtil.setGroundTypeLayerArea(xs, zs, xw, zw, xh, zh, desc.groundType);
		end;
		
		if FS19_precisionFarming.g_precisionFarming.nitrogenMap ~= nil then
            FS19_precisionFarming.g_precisionFarming.nitrogenMap:postUpdateSprayArea(xs, zs, xw, zw, xh, zh, sprayType,sprayType, false, 1)
        end
	else -- PF not active call regular functions 
		if spec.isSubsoiler then
			FSDensityMapUtil.updateSubsoilerArea(xs, zs, xw, zw, xh, zh);
		end

		FSDensityMapUtil.eraseTireTrack(xs, zs, xw, zw, xh, zh);
		
		-- call default update spray area function
		changedArea, totalArea = FSDensityMapUtil.updateSprayArea(xs, zs, xw, zw, xh, zh, sprayType)
	end;	
	
	--local changedArea, totalArea = FSDensityMapUtil.updateSprayArea(xs, zs, xw, zw, xh, zh, sprayType)
	spec.workAreaParameters.isActive = true
	spec.workAreaParameters.lastChangedArea = spec.workAreaParameters.lastChangedArea + changedArea
	spec.workAreaParameters.lastStatsArea = spec.workAreaParameters.lastStatsArea + changedArea
	spec.workAreaParameters.lastTotalArea = spec.workAreaParameters.lastTotalArea + totalArea

	if self:getLastSpeed() > 1 then
		spec.isWorking = true
	end

	return changedArea, totalArea
end;
