KroneBigPack = {};

function KroneBigPack.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Fillable, specializations) and SpecializationUtil.hasSpecialization(Baler, specializations);
end;

function KroneBigPack:load(xmlFile)

		self.rotpart = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.rotpart#index"));
        self.rotpart2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.rotpart2#index"));
		self.rotpart3 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.rotpart3#index"));
		---self.capacity = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.capacity"), 0.0);
		
			self.extraParticleSystems = {};
			local extraParticleSystemCount = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.extraParticleSystems#count"), 0);
			for i=1, extraParticleSystemCount do
				local namei = string.format("vehicle.extraParticleSystems.extraParticleSystem%d", i);
				Utils.loadParticleSystem(xmlFile, self.extraParticleSystems, namei, self.components, false, nil, self.baseDirectory)
			end;
			
			self.PickupParticleSystems = {};
			local PickupParticleSystemCount = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.PickupParticleSystems#count"), 0);
			for i=1, PickupParticleSystemCount do
				local namei = string.format("vehicle.PickupParticleSystems.PickupParticleSystem%d", i);
				Utils.loadParticleSystem(xmlFile, self.PickupParticleSystems, namei, self.components, false, nil, self.baseDirectory)
			end;
	
		self.previousLevel = 0;
		Utils.setEmittingState(self.extraParticleSystems, false)
		Utils.setEmittingState(self.PickupParticleSystems, false)
		self.empty = false
		self.lastDeltaFill = 0;
		self.collectLastFillLevel = 0;
		
		self.saveMinimumRpm = 0;	
		
		self.File = Utils.getFilename("Textures/hud.dds", self.baseDirectory);
		self.hudPoxX = 0.685;
		self.hudPoxY = 1-0.066; 
		self.hudWidth = 0.13325;
		self.hudHeight = 0.0513825;
		self.HUDKrone = Overlay:new("HUDKrone", self.File, self.hudPoxX, self.hudPoxY, self.hudWidth, self.hudHeight);
		self.HUD = false;
		self.lastBaleCount = 0;
	
		
		self.baleCount = 0;
		
end;


function KroneBigPack:delete()
	Utils.deleteParticleSystem(self.extraParticleSystems);
	Utils.deleteParticleSystem(self.PickupParticleSystems);
	
end;

function KroneBigPack:mouseEvent(posX, posY, isDown, isUp, button)
end;

function KroneBigPack:keyEvent(unicode, sym, modifier, isDown)
end;

function KroneBigPack:update(dt)
	self.lastBaleCount = table.getn(self.bales);
	
	if self.lastBale == nil and table.getn(self.bales) > 0 then
		self.lastBale = self.bales[1];
	else
		if self.bales[1] ~= self.lastBale then
			self.baleCount = self.baleCount + 1;
			self.lastBale = self.bales[1];
		end;		
	end;
end;

 
function KroneBigPack:updateTick(dt)
	local deltaFill = 0;
	if self.isClient then
		if self.collectLastFillLevel ~= self.fillLevel then
			if self.fillLevel > self.collectLastFillLevel then
				deltaFill = self.fillLevel - self.collectLastFillLevel;
			else
				deltaFill = self.lastDeltaFill;
			end;			
			self.collectLastFillLevel = self.fillLevel;
			self.lastFillChangeTime = self.time;
		end	
	end;
	
	if self:getIsActive() then
			
			
			if self.isClient then
				if deltaFill ~= 0 then
					Utils.setEmittingState(self.extraParticleSystems, true)
					Utils.setEmittingState(self.PickupParticleSystems, true);
				else	
					Utils.setEmittingState(self.extraParticleSystems, false)
					Utils.setEmittingState(self.PickupParticleSystems, false);
				end;
			end;
	
			if self.isTurnedOn then
						local fuelUsed = 0.0051;
						--renderText(0.1, 0.3, 0.021, tostring("self.fuelUsage: " .. fuelUsed));		
						self.attacherVehicle:setFuelFillLevel(self.attacherVehicle.fuelFillLevel-fuelUsed);
						g_currentMission.missionStats.fuelUsageTotal = g_currentMission.missionStats.fuelUsageTotal + fuelUsed;
						g_currentMission.missionStats.fuelUsageSession = g_currentMission.missionStats.fuelUsageSession + fuelUsed;
					
				rotate(self.rotpart, dt*0.021, 0, 0);
				rotate(self.rotpart2, dt*0.021, 0, 0);
				rotate(self.rotpart3, dt*0.03, 0, 0);
			end
			
			
			if InputBinding.hasEvent(InputBinding.HUD_ON) then
				self.HUD = not self.HUD;
			end;
			
			if InputBinding.hasEvent(InputBinding.EJECT) then
				self.bEmptyBaler = not self.bEmptyBaler
				self.fillLevel = 0
				self.fillType = Fillable.FILLTYPE_UNKNOWN
			end
	end;
		
	
	
	
	if self.attacherVehicle ~= nil then
		if self.attacherVehicle.motor ~= nil then
			
			if self.isTurnedOn == true then
				if self.attacherVehicle.motor.minRpm == self.saveMinimumRpm then
					self.attacherVehicle.motor.minRpm = math.max(self.attacherVehicle.motor.minRpm-900, -900);
				end;
				
			else
				if self.attacherVehicle.motor.minRpm ~= self.saveMinimumRpm then
					self.attacherVehicle.motor.minRpm = self.saveMinimumRpm;
				end;
			end;
		end;		
	end;	
			
			
			
	if self.isServer then
		if self.bEmptyBaler and self.lastBaleCount > 0 then	
		if self.isServer then
			if self.time > self.baleLastPositionTime+100 then
				for i=1, table.getn(self.bales) do
					local bale = self.bales[i];
					bale.lastX, bale.lastY, bale.lastZ = getWorldTranslation(bale.id);
				end;
				self.baleLastPositionTime = self.time;
			end;
		end;		
		
			local done = true;
			--for k, bale in pairs(self.bales) do
			for k=table.getn(self.bales), 1, -1 do
				local bale = self.bales[k];
				if bale.time > 0.4 then
					local sendTime = math.min(1.0, bale.time+(dt/10000));
					--Baler.setBaleTime(self, k, sendTime);
					
					
					if self.baleAnimCurve ~= nil then
						local bale = self.bales[k];
						bale.time = sendTime;
						local v = self.baleAnimCurve:get(bale.time);
						setTranslation(bale.id, v[1], v[2], v[3]);
						setRotation(bale.id, v[4], v[5], v[6]);
						if bale.time >= 1 then
							--Baler.dropBale(self, k);
							
							--local baleIndex = k;						
							--local bale = self.bales[baleIndex];
							local deltaRealTime = (self.time - self.baleLastPositionTime)/1000;
							if self.time == self.baleLastPositionTime then
								deltaRealTime = 1;
							end;
							local x,y,z = getWorldTranslation(bale.id);
							local rx,ry,rz = getWorldRotation(bale.id);
							--link(getRootNode(), bale.id);

							--if self.isServer then
								local baleObject = Bale:new(self.isServer, self.isClient);
								baleObject:load(bale.filename, x,y,z,rx,ry,rz);
								baleObject:register();

								local lx, ly, lz = bale.lastX, bale.lastY, bale.lastZ;
								
								setLinearVelocity(baleObject.nodeId, (x-lx)/deltaRealTime, (y-ly)/deltaRealTime, (z-lz)/deltaRealTime);
								--setLinearVelocity(baleObject.nodeId, 0, 0, 0);
							--end;
							delete(bale.id);
							table.remove(self.bales, k);

							-- increase bale count if variable exists (baling mission)
							if g_currentMission.baleCount ~= nil then
								g_currentMission.baleCount = g_currentMission.baleCount + 1;
							end;
												
						end;
						
						if self.isServer then
							if noEventSend == nil or not noEventSend then
								g_server:broadcastEvent(BalerSetBaleTimeEvent:new(self, k, bale.time), nil, nil, self);
							end;
						end;
						
					end;		
					
					done = false;
				end;
			end; 
			self.bEmptyBaler = (not done); -- and self.lastBaleCount > 1;
		end;
		
		if self.bEmptyBaler then
			if self.attacherVehicle ~= nil then
				local kmh = self.attacherVehicle.lastSpeed*self.attacherVehicle.speedDisplayScale*3600;
				if kmh < 10 then
					self.attacherVehicle.motor:setSpeedLevel(1, true);
					self.attVehMoving = true;
				else
					self.attacherVehicle.motor:setSpeedLevel(0, false);
					self.attVehMoving = false;
				end;
			end;
		elseif self.attVehMoving == true then
			if self.attacherVehicle ~= nil then
				self.attacherVehicle.motor:setSpeedLevel(0, false);
			end;
			self.attVehMoving = false;
		end;
	end;
end;





function KroneBigPack:readStream(streamId, connection)
	self.baleCount = streamReadFloat32(streamId);
end;

function KroneBigPack:writeStream(streamId, connection)	
	streamWriteFloat32(streamId, self.baleCount);
end;

--function KroneBigPack:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)		-- gets never ever called ?!
--print("function KroneBigPack:loadFromAttributesAndNodes("..tostring(xmlFile)..", "..tostring(key)..", "..tostring(resetVehicles));
--	if resetVehicles then
--		self.baleCount = 0;
--	end;
--end;



function KroneBigPack:onAttach(attacherVehicle)
	self.attacherVehicle = attacherVehicle;
	if self.attacherVehicleCopy1 == nil then
		self.attacherVehicleCopy1 = self.attacherVehicle;
	end;
	if self.attacherVehicle.motor ~= nil then
		self.saveMinimumRpm = self.attacherVehicle.motor.minRpm;
	else
		if self.attacherVehicle.saveMinRpm ~= nil then
			self.saveMinimumRpm = self.attacherVehicle.saveMinimumRpm;
		else
			self.attacherVehicle.saveMinimumRpm  = 100;
		end;
	end;
end;	

function KroneBigPack:onDetach()
	for k, steerable in pairs(g_currentMission.steerables) do
		if self.attacherVehicleCopy1 == steerable then
			self.attacherVehicleCopy1 = nil;
		end;
	end;
end;


function KroneBigPack:onLeave()
		Utils.setEmittingState(self.extraParticleSystems, false)
		Utils.setEmittingState(self.PickupParticleSystems, false)
		self.attacherVehicle.motor.minRpm = self.standardMinRpm
end;

function KroneBigPack:draw()
		if self.HUD then
			self.HUDKrone:render();
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("HUD_OFF"), self.typeDesc), InputBinding.HUD_ON);
			setTextBold(true);
			totalBalesCountString = string.format("%d", self.TotalBalesCount);
			renderText(0.75, 0.951, 0.02, string.format(totalBalesCountString));
			self.HUDKrone:render();
		else
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("HUD_ON"), self.typeDesc), InputBinding.HUD_ON);	
		end;
		
		if self:getIsActive() then
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("UNLOAD"), self.typeDesc), InputBinding.EJECT);
		end
end;

 function KroneBigPack:onDeactivate()
	Utils.setEmittingState(self.extraParticleSystems, false)
	Utils.setEmittingState(self.PickupParticleSystems, false)
end;




