-- LemkenOpal
-- 
--
-- @ Autor  FireAndIce (www.bm-modding.de), sven777b
-- @ Last Edit  20/12/2012

LemkenOpal = {};

function LemkenOpal.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Plough, specializations); 
end;

function LemkenOpal:load(xmlFile)

    self.hosesDeatached = Utils.indexToObject(self.components, "0>2|5|0");
    self.hosesDeatachedInverted = Utils.indexToObject(self.components, "0>2|5|1");
    self.joint = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.joint#index"));
	self.move = 0;
	self.moveBack = 0;
	
end;

function LemkenOpal:delete()
end;

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

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

function LemkenOpal:update(dt)
	
	local _,yt,_ = getTranslation(self.joint);
	local x,y,z = getWorldTranslation(self.rootNode);
	local dist = 0;
	if self.lastWP ~= nil then
		dist = Utils.vector2Length(self.lastWP[1]-x , self.lastWP[3]-z);
	end;
	
	if self:getIsActive() then
		if self.isClient then
			if self.ploughHasGroundContact then
				local lastMove = self.move;
--				if self.movingDirection ~= 1 then
				if self.rotationMax then
					self.move = -dist/10;
				else
					self.move = dist/10;
				end;
				self.move = math.max(-0.30 , math.min(0.30,self.move));
				if self.movingDirection == 1 and lastMove ~= self.move then
					setTranslation (self.joint, 0, (self.move), -1.66207)
					setJointFrame(self.componentJoints[1].jointIndex, 0, self.componentJoints[1].jointNode);
				end;
			else
				self.lastWP = {x,y,z};
				if yt ~= 0 then
					self.moveBack = yt * 0.93
					if self.moveBack < 0.1 and self.moveBack > -0.1 then
						self.moveBack = 0
						self.move = 0;
					end;
					setTranslation (self.joint, 0, self.moveBack, -1.66207)
					setJointFrame(self.componentJoints[1].jointIndex, 0, self.componentJoints[1].jointNode);
				end;
			end;
		end;
	end;
        		
end;
	
function LemkenOpal:updateTick(dt)
    if self:getIsAnimationPlaying(self.rotationPart.turnAnimation) then
        setJointRotationLimit(self.componentJoints[2].jointIndex, 0, true, Utils.degToRad(-90), Utils.degToRad(90));
    else
        setJointRotationLimit(self.componentJoints[2].jointIndex, 0, true, Utils.degToRad(-145), Utils.degToRad(145));
    end;    	
end;
 
function LemkenOpal:draw()
end;

function LemkenOpal:onAttach()
    setVisibility(self.skinnedNodes[1], true);
    setVisibility(self.skinnedNodes[2], true);
    setVisibility(self.hosesDeatached, false);
    setVisibility(self.hosesDeatachedInverted, false);
end;

function LemkenOpal:onDetach()
    setVisibility(self.skinnedNodes[1], false);
    setVisibility(self.skinnedNodes[2], false);
    if self.rotationMax then
        setVisibility(self.hosesDeatachedInverted, true);
    else
        setVisibility(self.hosesDeatached, true);
    end;
end;