--
-- Rufa
--
-- M@D Author:  Heady
-- M@D date: 21.06.2011
--
-- > Copyright (C) Heady - www.planet-ls.de < --
--

Rufa = {};

function Rufa.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(AnimatedVehicle, specializations);
end;

function Rufa:load(xmlFile)
	
	local rufa = {};
    rufa.name = getXMLString(xmlFile, "vehicle.rufa#name");
    rufa.openSpeedScale = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.rufa#upSpeedScale"), 1);
    rufa.closeSpeedScale = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.rufa#downSpeedScale"), -rufa.openSpeedScale);
    if rufa.name ~= nil then
        self.rufa = rufa;
    end;
	self.rufa.active = false;
	self.rufaActive = false;
	self.accDirection = 1;
	
	self.wheelsRotSpeedBackup = {};
	for i=1, table.getn(self.wheels) do
		self.wheelsRotSpeedBackup[i] = self.wheels[i].rotSpeed;
	end;
	
end;

function Rufa:delete()
end;

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

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

function Rufa:readStream(streamId, connection)
	self.accDirection = streamReadFloat32(streamId);	
	self.rufa.active = streamReadBool(streamId);
end;

function Rufa:writeStream(streamId, connection)
	streamWriteFloat32(streamId, self.accDirection);	
	streamWriteBool(streamId, self.rufa.active);
end;

function Rufa:update(dt)

	if self:getIsActiveForInput() then			
		
		if InputBinding.hasEvent(InputBinding.RUFA) then
			self.rufa.active = not self.rufa.active;
		end;			

	end;
	
end;

function Rufa:updateTick(dt)

	if self.rufaActive ~= self.rufa.active then		
		if self.rufa.active then
			self:playAnimation(self.rufa.name, self.rufa.openSpeedScale, self:getAnimationTime(self.rufa.name));
			for i=1, table.getn(self.wheels) do				
				self.wheels[i].rotSpeed = -self.wheelsRotSpeedBackup[i];
			end;
			self.accDirection = -1;
		else	
			self:playAnimation(self.rufa.name, self.rufa.closeSpeedScale, self:getAnimationTime(self.rufa.name)); 
			for i=1, table.getn(self.wheels) do				
				self.wheels[i].rotSpeed = self.wheelsRotSpeedBackup[i];
			end;
			self.accDirection = 1;				
		end;		
		
		RufaMPEvent:updateSendEvent(self);	
	end;

	self.rufaActive = self.rufa.active;

end;

function Rufa:draw()	
end;


local wheelsUtilUpdateWheelsPhysics = WheelsUtil.updateWheelsPhysics;

function WheelsUtil.updateWheelsPhysics(self, dt, currentSpeed, acceleration, doHandbrake, requiredDriveMode)

	if self.accDirection ~= nil then
		acceleration = acceleration*self.accDirection;
	end;
	
	wheelsUtilUpdateWheelsPhysics(self, dt, currentSpeed, acceleration, doHandbrake, requiredDriveMode);
end;
