--
-- BuyableDistributor
-- Class for BuyableDistributor
--
-- @author  Stefan Maurus - www.stefanmaurus.de
-- @date  30.05.2012
--
-- @last update  08.02.2013
--
 
BuyableDistributor = {};
  
function BuyableDistributor.prerequisitesPresent(specializations)
      return true;
end;

function BuyableDistributor:load(xmlFile)

	self.help = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.BuyableDistributor#help"));		
	self.pallet = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.BuyableDistributor#pallet"));		
	self.belt = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.BuyableDistributor#belt"));
	self.distributor = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.BuyableDistributor#distributor"));
	self.distributorTransX, self.distributorTransY, self.distributorTransZ = getTranslation(self.distributor)
	self.distributorRotX, self.distributorRotY, self.distributorRotZ = getRotation(self.distributor)	
	self.Attacher = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.attacherJoint#index"));	
	
	self.isStatic = getXMLString(xmlFile, "vehicle.sprayParticleSystem#static");
	--Particlesystem
	self.sprayValves = {};
	local psFile = getXMLString(xmlFile, "vehicle.sprayParticleSystem#file");
    if psFile ~= nil then
        local i=0;
        while true do
            local baseName = string.format("vehicle.sprayValves.sprayValve(%d)", i);
            local node = getXMLString(xmlFile, baseName.. "#index");
            if node == nil then
                break;
            end;
            node = Utils.indexToObject(self.components, node);
            if node ~= nil then
                local sprayValve = {};
                sprayValve.particleSystems = {};
				if self.isStatic == "true" then
					Utils.loadStaticParticleSystem(xmlFile, sprayValve.particleSystems, "vehicle.sprayParticleSystem", node, false, nil, self.baseDirectory);	
				else
					Utils.loadParticleSystem(xmlFile, sprayValve.particleSystems, "vehicle.sprayParticleSystem", node, false, nil, self.baseDirectory);
				end;
                table.insert(self.sprayValves, sprayValve);
            end;
            i = i+1;
        end;
    end;	
	
	-- Cutting Areas	
	self.cuttingAreas1 = {};
	self.cuttingAreas1.startIndex = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.cuttingAreasUpdate#startIndex1"));		
	self.cuttingAreas1.widthIndex = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.cuttingAreasUpdate#widthIndex1"));		
	self.cuttingAreas1.heightIndex = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.cuttingAreasUpdate#heightIndex1"));		
	self.cuttingAreas2 = {};
	self.cuttingAreas2.startIndex = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.cuttingAreasUpdate#startIndex2"));		
	self.cuttingAreas2.widthIndex = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.cuttingAreasUpdate#widthIndex2"));		
	self.cuttingAreas2.heightIndex = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.cuttingAreasUpdate#heightIndex2"));		

	self.CuttingAreasIsOnOwnedField = false;
	
	self.notYourFieldWaringTime = 0;
end;

function BuyableDistributor:delete()
	for k,sprayValve in pairs(self.sprayValves) do
		Utils.deleteParticleSystem(sprayValve.particleSystems);
	end;
end;

function BuyableDistributor:readStream(streamId, connection)
end;

function BuyableDistributor:writeStream(streamId, connection) 
end;

function BuyableDistributor:mouseEvent(posX, posY, isDown, isUp, button)
end;
 
function BuyableDistributor:keyEvent(unicode, sym, modifier, isDown)
end;

function BuyableDistributor:update(dt)	

	local A1x1,_,A1z1 = getWorldTranslation(self.cuttingAreas1.startIndex);
	local A1x2,_,A1z2 = getWorldTranslation(self.cuttingAreas1.widthIndex);
	local A1x3,_,A1z3 = getWorldTranslation(self.cuttingAreas1.heightIndex);	
	local A2x1,_,A2z1 = getWorldTranslation(self.cuttingAreas2.startIndex);
	local A2x2,_,A2z2 = getWorldTranslation(self.cuttingAreas2.widthIndex);
	local A2x3,_,A2z3 = getWorldTranslation(self.cuttingAreas2.heightIndex);
	if g_currentMission:getIsFieldOwnedAtWorldPos(A1x1,A1z1) and g_currentMission:getIsFieldOwnedAtWorldPos(A1x2,A1z2) and g_currentMission:getIsFieldOwnedAtWorldPos(A1x3,A1z3) then
		if g_currentMission:getIsFieldOwnedAtWorldPos(A2x1,A2z1) and g_currentMission:getIsFieldOwnedAtWorldPos(A2x2,A2z2) and g_currentMission:getIsFieldOwnedAtWorldPos(A2x3,A2z3) then
			self.CuttingAreasIsOnOwnedField = true;
		else
			self.CuttingAreasIsOnOwnedField = false;
		end;
	else
		self.CuttingAreasIsOnOwnedField = false;
	end;

	if self.attacherVehicle ~= nil then
		if not self.attacherVehicle.distributerIsAttached then
			self.attacherVehicle.distributerIsAttached = true;
		end;
		if self.attacherVehicle.isTurnedOn and not self.CuttingAreasIsOnOwnedField then
			self.attacherVehicle.isTurnedOn = false;
			if self.attacherVehicle.spraySoundEnabled then
				stopSample(self.attacherVehicle.spraySound);
				self.attacherVehicle.spraySoundEnabled = false;
			end;
			self.attacherVehicle.speedViolationTimer = self.attacherVehicle.speedViolationMaxTime;
			self.notYourFieldWaringTime = self.time + 3000;
		end;
				
		if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA) and not self.CuttingAreasIsOnOwnedField then
			self.notYourFieldWaringTime = self.time + 3000;
		end;

		if self.attacherVehicle.isTurnedOn and math.abs(self.attacherVehicle.speedViolationTimer - self.attacherVehicle.speedViolationMaxTime) < 2 and self.CuttingAreasIsOnOwnedField then
			if self.attacherVehicle.fillLevel > 0 then
				local x, y, z = getWorldTranslation(self.cuttingAreas1.startIndex)
				local x1, y1, z1 = getWorldTranslation(self.cuttingAreas1.widthIndex)
				local x2, y2, z2 = getWorldTranslation(self.cuttingAreas1.heightIndex)
				local old1, total1 = Utils.getFruitWindrowArea(FruitUtil.FRUITTYPE_LIQUIDMANURE, x, z, x1, z1, x2, z2);
				local value1 = 1+math.floor(old1 / total1 + 0.7);
				value1 = math.min(value1, g_currentMission.maxWindrowValue);				
				Utils.updateFruitWindrowArea(FruitUtil.FRUITTYPE_LIQUIDMANURE, x, z, x1, z1, x2, z2, value1, true, false)
				Utils.updateSprayArea(x, z, x1, z1, x2, z2);

				local x2, y2, z2 = getWorldTranslation(self.cuttingAreas2.startIndex)
				local x12, y12, z12 = getWorldTranslation(self.cuttingAreas2.widthIndex)
				local x22, y22, z22 = getWorldTranslation(self.cuttingAreas2.heightIndex)
				local old2, total2 = Utils.getFruitWindrowArea(FruitUtil.FRUITTYPE_LIQUIDMANURE, x2, z2, x12, z12, x22, z22);
				local value2 = 1+math.floor(old2 / total2 + 0.7);
				value2 = math.min(value2, g_currentMission.maxWindrowValue);				
				Utils.updateFruitWindrowArea(FruitUtil.FRUITTYPE_LIQUIDMANURE, x2, z2, x12, z12, x22, z22, value2, true, false)
				Utils.updateSprayArea(x2, z2, x12, z12, x22, z22);

				local x, y, z = getWorldTranslation(self.cuttingAreas1.startIndex)
				local x1, y1, z1 = getWorldTranslation(self.cuttingAreas1.widthIndex)
				local x2, y2, z2 = getWorldTranslation(self.cuttingAreas1.heightIndex)
				local old1, total1 = Utils.getFruitWindrowArea(FruitUtil.FRUITTYPE_MANURELIQUID, x, z, x1, z1, x2, z2);
				local value1 = 1+math.floor(old1 / total1 + 0.7);
				value1 = math.min(value1, g_currentMission.maxWindrowValue);				
				Utils.updateFruitWindrowArea(FruitUtil.FRUITTYPE_MANURELIQUID, x, z, x1, z1, x2, z2, value1, true, false)
				Utils.updateSprayArea(x, z, x1, z1, x2, z2);
								
				local x2, y2, z2 = getWorldTranslation(self.cuttingAreas2.startIndex)
				local x12, y12, z12 = getWorldTranslation(self.cuttingAreas2.widthIndex)
				local x22, y22, z22 = getWorldTranslation(self.cuttingAreas2.heightIndex)
				local old2, total2 = Utils.getFruitWindrowArea(FruitUtil.FRUITTYPE_MANURELIQUID, x2, z2, x12, z12, x22, z22);
				local value2 = 1+math.floor(old2 / total2 + 0.7);
				value2 = math.min(value2, g_currentMission.maxWindrowValue);				
				Utils.updateFruitWindrowArea(FruitUtil.FRUITTYPE_MANURELIQUID, x2, z2, x12, z12, x22, z22, value2, true, false)
				Utils.updateSprayArea(x2, z2, x12, z12, x22, z22);
			
				for k,sprayValve in pairs(self.sprayValves) do
					Utils.setEmittingState(sprayValve.particleSystems, true);		
				end;
			end;
		else
            for k,sprayValve in pairs(self.sprayValves) do
                Utils.setEmittingState(sprayValve.particleSystems, false);
            end;		
		end; 
	end;
end;

function BuyableDistributor:updateTick(dt)
end;

function BuyableDistributor:draw()
	if self.notYourFieldWaringTime > self.time then
		g_currentMission:addWarning(g_i18n:getText("You_dont_own_this_field"));
	end;
end;
 
function BuyableDistributor:onDetach()
	setVisibility(self.pallet, true);
	setVisibility(self.belt, true);
	setTranslation(self.distributor, self.distributorTransX, self.distributorTransY, self.distributorTransZ)
	setRotation(self.distributor, self.distributorRotX, self.distributorRotY, self.distributorRotZ)
end;

function BuyableDistributor:onAttach()
	setVisibility(self.pallet, false);
	setVisibility(self.belt, false);
	local TransX, TransY, TransZ = getTranslation(self.Attacher)	
	setTranslation(self.distributor, TransX, TransY, TransZ)
	local RotX, RotY, RotZ = getRotation(self.Attacher)		
	setRotation(self.distributor, RotX, RotY, RotZ)	
end;

function BuyableDistributor:onLeave()
end;
 
function BuyableDistributor:onDeactivate()
end;
  
function BuyableDistributor: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;