--[[
	BalerFix
	Specialization to allow pressing bales with an stationary baler!
	
	@author:    Ifko[nator]
	@date:      11.09.2020
	@version:	1.0
]]

BalerFix = {};

function BalerFix.prerequisitesPresent(specializations)
	return SpecializationUtil.hasSpecialization(Baler, specializations);
end;

function BalerFix.registerEventListeners(vehicleType)
	local functionNames = {
		"onLoad",
		"onUpdateTick"
	};
	
	for _, functionName in ipairs(functionNames) do
		SpecializationUtil.registerEventListener(vehicleType, functionName, BalerFix);
	end;
end;

function BalerFix:onLoad(savegame)
	local specBaler = self.spec_baler;

	specBaler.isStationary = Utils.getNoNil(getXMLBool(self.xmlFile, "vehicle.baler#isStationary"), false);
	specBaler.oldFillLevel = self:getFillUnitFillLevel(specBaler.fillUnitIndex);
	specBaler.doCloseBalingChamber = false;
end;

function BalerFix:onUpdateTick(dt, isActiveForInput, isActiveForInputIgnoreSelection, isSelected)
	local specBaler = self.spec_baler;
	
	if self.isServer and specBaler.isStationary then
		local pickedUpLiters = self:getFillUnitFillLevel(specBaler.fillUnitIndex);

		if pickedUpLiters > 0 then
			if specBaler.baleUnloadAnimationName == nil then
				--## square bales
				
				if pickedUpLiters ~= specBaler.oldFillLevel then
					local deltaLevel = pickedUpLiters * specBaler.fillScale;
					local deltaTime = self:getTimeFromLevel(deltaLevel / dt);

					self:moveBales(deltaTime);
					
					specBaler.oldFillLevel = pickedUpLiters;
				end;
			else
				--## round bales
				
				local capacity = self:getFillUnitCapacity(specBaler.fillUnitIndex);
				local percentage = pickedUpLiters / capacity;

				if percentage == 1 then	
					self:setIsUnloadingBale(self:isUnloadingAllowed());

					specBaler.doCloseBalingChamber = true;
				end;
			end;
		end;

		if specBaler.unloadingState == Baler.UNLOADING_OPEN and specBaler.doCloseBalingChamber then
			self:setIsUnloadingBale(false);

			specBaler.doCloseBalingChamber = false;
		end;
	end;
end;