--
-- TebbeHS180SilageEdition
-- Class for the Tebbe HS 180 Silage Edition
--
-- @author  Stefan Maurus, www.stefanmaurus.de
-- @date  20/11/11
--
 
TebbeHS180SilageEdition = {};
  
function TebbeHS180SilageEdition.prerequisitesPresent(specializations)
      return true;
end;

function TebbeHS180SilageEdition:load(xmlFile)
	 	 
    self.rotatingPartsAnimTime = 0;
  
    self.rotatingParts = {};
    local i=0;
    while true do
        local baseName = string.format("vehicle.rotatingParts.rotatingPart(%d)", i);
        if not hasXMLProperty(xmlFile, baseName) then
            break;
        end;
        local entry = {};
        entry.node = Utils.indexToObject(self.components, getXMLString(xmlFile, baseName.. "#node"));
        entry.speed = Utils.getNoNil(getXMLFloat(xmlFile, baseName.. "#speed"), 0.005);
        if entry.node ~= nil then
            table.insert(self.rotatingParts, entry);
        end;
        i = i+1;
    end;
	
	self.showPS = false;
	self.particleSystem1 = {};
    local i = 0;
    while true do
        local system1i = string.format("vehicle.particleSystem1.system(%d)", i);
		local index1i = Utils.indexToObject(self.components, getXMLString(xmlFile, system1i .. "#index"));
		if index1i == nil then
			break;
		end; 
        Utils.loadStaticParticleSystem(xmlFile, self.particleSystem1, system1i, index1i, false, nil, self.baseDirectory)		
		i = i +1;		
    end;	
	
	self.hayBase = {};
	self.hayBase.node = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.hayBase#index"));
	self.hayBase.unloadingSpeed = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.hayBase#unloadingSpeed"), 0.001);
	self.hayBase.unloadingDirection = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.hayBase#unloadingDirection"), 1);
	setShaderParameter(self.hayBase.node, "movingDirection", 0,0,0,0,false);
	
	self.lostChaff = {};
	self.lostChaff.Index1 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.lostChaff#index1"));	
	self.lostChaff.Index2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.lostChaff#index2"));	
	self.lostChaff.filePath = getXMLString(xmlFile, "vehicle.lostChaff#filePath");
	self.isOnField = false;
end;

function TebbeHS180SilageEdition:delete()
	Utils.setEmittingState(self.particleSystem1, false);	
end;

function TebbeHS180SilageEdition:readStream(streamId, connection)
end;

function TebbeHS180SilageEdition:writeStream(streamId, connection)
end;

function TebbeHS180SilageEdition:mouseEvent(posX, posY, isDown, isUp, button)
end;
 
function TebbeHS180SilageEdition:keyEvent(unicode, sym, modifier, isDown)
end;
 
function TebbeHS180SilageEdition:update(dt)
	if self:getIsActiveForInput() then
		if InputBinding.hasEvent(InputBinding.HONK) then
			self.fillLevel = self.fillLevel+1000;	
		end;	
		if InputBinding.hasEvent(InputBinding.LOWER_IMPLEMENT) then
			self.fillLevel = self.fillLevel-1000;	
		end;			
	end;
end;

function TebbeHS180SilageEdition:updateTick(dt)
    if self.tipState == Trailer.TIPSTATE_OPENING or self.tipState == Trailer.TIPSTATE_OPEN and self:getIsActive() then
        self.rotatingPartsAnimTime = self.rotatingPartsAnimTime + dt;
        for _, rotatingPart in ipairs(self.rotatingParts) do
            setRotation(rotatingPart.node, 0 , rotatingPart.speed*self.rotatingPartsAnimTime, 0);
        end;
		setShaderParameter(self.hayBase.node, "movingDirection", self.hayBase.unloadingDirection*self.hayBase.unloadingSpeed,0,0,0,false);	
		if self.fillLevel > 1 then
			Utils.setEmittingState(self.particleSystem1, true);		
		else
			Utils.setEmittingState(self.particleSystem1, false);	
		end;
	else
		setShaderParameter(self.hayBase.node, "movingDirection", 0,0,0,0,false);	
		Utils.setEmittingState(self.particleSystem1, false);	
    end;
	if self.fillLevel <= 0 or self.tipState == Trailer.TIPSTATE_OPENING then
		Utils.setEmittingState(self.dischargeParticleSystems[self.currentFillType], false);
	end;
	
	local x,y,z = getWorldTranslation(self.lostChaff.Index1);
	local cultivatorChannel = Utils.getDensity(g_currentMission.terrainDetailId, g_currentMission.cultivatorChannel, x, z, x, z, x, z);
	local ploughChannel = Utils.getDensity(g_currentMission.terrainDetailId, g_currentMission.ploughChannel, x, z, x, z, x, z);
	local sowingChannel = Utils.getDensity(g_currentMission.terrainDetailId, g_currentMission.sowingChannel, x, z, x, z, x, z);
	if cultivatorChannel > 0 or ploughChannel > 0 or sowingChannel > 0 then	
		self.isOnField = true;
	else
		self.isOnField = false;
	end;
	
	if self.fillLevel > 90 and self.lastSpeed*3600 > 30 or self.fillLevel > 50 and self.isOnField and self.lastSpeed*3600 > 5 then
		local randomWert = math.random(0,1000)
		if randomWert == 80 then
			local GroundRoot = Utils.loadSharedI3DFile(self.lostChaff.filePath, self.baseDirectory);
			local GroundId = getChildAt(GroundRoot, 0);
			setRigidBodyType(GroundId, "None");
			link(getRootNode(), GroundId);
			delete(GroundRoot);
			local x,y,z = getWorldRotation(self.lostChaff.Index1);
			setRotation(GroundId, x,y,z);
			local x,y,z = getWorldTranslation(self.lostChaff.Index1);
			setTranslation(GroundId, x,y,z);
			local fillLost = math.random(10,40)
			self.fillLevel = self.fillLevel-fillLost;	
		elseif randomWert == 880 then
			local GroundRoot = Utils.loadSharedI3DFile(self.lostChaff.filePath, self.baseDirectory);
			local GroundId = getChildAt(GroundRoot, 0);
			setRigidBodyType(GroundId, "None");
			link(getRootNode(), GroundId);
			delete(GroundRoot);
			local x,y,z = getWorldRotation(self.lostChaff.Index2);
			setRotation(GroundId, x,y,z);
			local x,y,z = getWorldTranslation(self.lostChaff.Index2);
			setTranslation(GroundId, x,y,z);
			local fillLost = math.random(10,40)
			self.fillLevel = self.fillLevel-fillLost;						
		end;
	end;
end;
 
function TebbeHS180SilageEdition:draw()
end;
 
function TebbeHS180SilageEdition:onDetach()
end;

function TebbeHS180SilageEdition:onLeave()
end;
 
function TebbeHS180SilageEdition:onDeactivate()
end;
  
function TebbeHS180SilageEdition:onDeactivateSounds()
end;

Utils.loadStaticParticleSystem = function(xmlFile, psTable, baseString, linkNode, defaultEmittingState, filename, baseDirectory)
	--
	-- Static Particle System
	--
	-- Author:  Heady | www.planet-ls.de
	-- Date: 30.04.2011
	--
	--
	
	local defaultLinkNode = linkNode;
		if type(linkNode) == "table" then
			defaultLinkNode = linkNode[1].node;
		end;
	local linkNode = Utils.getNoNil(Utils.indexToObject(linkNode, getXMLString(xmlFile, baseString .. "#node")), defaultLinkNode);

	local psFile = getXMLString(xmlFile, baseString .. "#file");
	if psFile == nil then
		psFile = filename;
	end;
	if psFile == nil then
		return;
	end;
	psFile = Utils.getFilename(psFile, baseDirectory);  
	local rootNode = loadI3DFile(psFile);
	if rootNode == 0 then
		print("Error: failed to load particle system " .. psFile);
		return;
	end	
	
	link(linkNode, rootNode)	

	local posString = getXMLString(xmlFile, baseString .. "#position");
	if posString ~= nil then
		local posX, posY, posZ = Utils.getVectorFromString(posString);
		setTranslation(rootNode, posX, posY, posZ);
	end;	
	local rotString = getXMLString(xmlFile, baseString .. "#rotation");
	if rotString ~= nil then
		local rotX, rotY, rotZ = Utils.getVectorFromString(rotString);
		rotX = Utils.degToRad(rotX);
		rotY = Utils.degToRad(rotY);
		rotZ = Utils.degToRad(rotZ);
		setRotation(rootNode, rotX, rotY, rotZ);
	end;

	--for i = getNumOfChildren(rootNode) - 1, 0, -1 do
	for i=1, getNumOfChildren(rootNode) do
		local child = getChildAt(rootNode, i-1);
		if getClassName(child) == "Shape" then
			local geometry = getGeometry(child);
			if geometry ~= 0 and getClassName(geometry) == "ParticleSystem" then
				table.insert(psTable, {geometry = geometry, shape = child});
				if defaultEmittingState ~= nil then
					setEmittingState(geometry, defaultEmittingState);
				end;
			end;
		end;
	end;

	return rootNode;
end;
