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

function BuyableDistributor:load(xmlFile)
	self.setSaveMode= SpecializationUtil.callSpecializationsFunction("setSaveMode"); 
	
	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.saveMode = false;
	
	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"));		
end;

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

function BuyableDistributor:readStream(streamId, connection)
	self:setSaveMode(streamReadBool(streamId), true);	
end;

function BuyableDistributor:writeStream(streamId, connection) 
	streamWriteBool(streamId, self.saveMode);
end;

function BuyableDistributor:setSaveMode(bool, noEventSend)
	self.saveMode = bool;
	SetSaveModeEvent.sendEvent(self, bool, noEventSend);
end;

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

function BuyableDistributor:update(dt)	
	if self.attacherVehicle ~= nil then
		if self.attacherVehicle.isTurnedOn and not self.attacherVehicle.wasToFast then
			if self.attacherVehicle.fillLevel > 0 then
				-- Area1
				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);
				--Area2	
				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);
				
				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;
	if self:getIsActiveForInput() then
		if InputBinding.hasEvent(InputBinding.saveMode) then
			self:setSaveMode(not self.saveMode);	
		end;	
	end;
	if self.saveMode then
		self.allowsDetaching = false;
	else
		self.allowsDetaching = true;
	end;
end;

function BuyableDistributor:updateTick(dt)
end;

function BuyableDistributor:draw()
	if self.saveMode then
		g_currentMission:addHelpButtonText(g_i18n:getText("saveModeOff"), InputBinding.saveMode);		
	else
		g_currentMission:addHelpButtonText(g_i18n:getText("saveModeOn"), InputBinding.saveMode);
	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;

--------------------
--*****EVENT*****--
--------------------


SetSaveModeEvent = {};
SetSaveModeEvent_mt = Class(SetSaveModeEvent, Event);

InitEventClass(SetSaveModeEvent, "SetSaveModeEvent");

function SetSaveModeEvent:emptyNew()
    local self = Event:new(SetSaveModeEvent_mt);
    self.className="SetSaveModeEvent";
    return self;
end;

function SetSaveModeEvent:new(vehicle, saveMode)
    local self = SetSaveModeEvent:emptyNew()
    self.vehicle = vehicle;
	self.saveMode = saveMode;
    return self;
end;

function SetSaveModeEvent:readStream(streamId, connection)
    local id = streamReadInt32(streamId);
    self.vehicle = networkGetObject(id);

	self.saveMode = streamReadBool(streamId);
	self.vehicle:setSaveMode(self.saveMode, true);

	if not connection:getIsServer() then
        g_server:broadcastEvent(SetSaveModeEvent:new(self.vehicle, self.saveMode), nil, connection, self.vehicle);
    end;
end;

function SetSaveModeEvent:writeStream(streamId, connection)
    streamWriteInt32(streamId, networkGetObjectId(self.vehicle));
	streamWriteBool(streamId, self.saveMode);
end;


function SetSaveModeEvent.sendEvent(vehicle, saveMode, noEventSend)
	if noEventSend == nil or noEventSend == false then
		if g_server ~= nil then
			g_server:broadcastEvent(SetSaveModeEvent:new(vehicle, saveMode), nil, nil, vehicle);
		else
			g_client:getServerConnection():sendEvent(SetSaveModeEvent:new(vehicle, saveMode));
		end;
	end;
end;