-- Advanced Trailer Steering script

-- 27/06/2013

-- script by Druptown (FMC) & Gate (FMC)

steeringMod = {};

function steeringMod.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Trailer, specializations);
end;

function steeringMod:load(xmlFile)
	self.steeringAxleUpdateBackwards = true;
end;

function steeringMod:delete()
	-- Do Nothing
end;

function steeringMod:mouseEvent(posX, posY, isDown, isUp, button)
	-- Do Nothing
end;

function steeringMod:keyEvent(unicode, sym, modifier, isDown)
	-- Do Nothing
end;

function steeringMod:update(deltaTime)
     if self:getIsActive() then
          if self.updateSteeringAxleAngle then
              if self.attacherVehicle ~= nil and (self.movingDirection >= 0 or self.steeringAxleUpdateBackwards) then
			  local x,y,z = worldDirectionToLocal(self.steeringAxleNode, localDirectionToWorld( self.components[2].node, 0, 0, 1));
                  local dot = z; -- 0*x + z*1;
                  dot = dot / Utils.vector2Length(x,z);
                  local angle = math.acos(dot);
                  if x < 0 then
                      angle = -angle;
                  end;
                  local startSpeed = self.steeringAxleAngleScaleStart;
                  local endSpeed = self.steeringAxleAngleScaleEnd;
                  local scale = Utils.clamp(1 + (self.lastSpeed*3600-startSpeed) * 1.0/(startSpeed-endSpeed), 0, 1);
                  self.steeringAxleAngle = angle*scale;
              else
                  self.steeringAxleAngle = 0;
              end;
          end;
  
          if self.firstTimeRun and self.updateWheels and self.isServer then
              local brakeForce = 0;
              if self.isBraking then
                  brakeForce = self.brakeForce;
              end;
              for _,wheel in pairs(self.wheels) do
                  setWheelShapeProps(wheel.node, wheel.wheelShape, 0, brakeForce, wheel.steeringAngle);
              end;
          end;
      end;
end;

function steeringMod:draw()
	-- Do Nothing
end;