-- d47
-- Bayn TSF3
-- Big thanks to guimchevalier for his script "Pince.lua"
-- 03-09-09
-- Automated Load/Unload added by Nibmeister
-- LS2011 Script: Burner


d47 = {};

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

function d47:load(xmlFile)	
		
	local translationPartNode = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.translationPart#index"));
    if translationPartNode ~= nil then
        self.translationPart = {};
        self.translationPart.node = translationPartNode;
        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.translationPart#minTrans"));
        self.translationPart.minTrans = {};
        self.translationPart.minTrans[1] = Utils.getNoNil(x, 0);
        self.translationPart.minTrans[2] = Utils.getNoNil(y, 0);
        self.translationPart.minTrans[3] = Utils.getNoNil(z, 0);

        x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.translationPart#maxTrans"));
        self.translationPart.maxTrans = {};
        self.translationPart.maxTrans[1] = Utils.getNoNil(x, 0);
        self.translationPart.maxTrans[2] = Utils.getNoNil(y, 0);
        self.translationPart.maxTrans[3] = Utils.getNoNil(z, 0);

        self.translationPart.transTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.translationPart#transTime"), 2)*1000;
        self.translationPart.touchTransLimit = Utils.getNoNil(getXMLString(xmlFile, "vehicle.translationPart#touchTransLimit"), 10);
    end;
    
	local rotationNode1 = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.rotation1#index"));
    if rotationNode1 ~= nil then
        self.rotation1 = {};
        self.rotation1.node = rotationNode1;
        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.rotation1#minRot"));
        self.rotation1.minRot = {};
        self.rotation1.minRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.rotation1.minRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.rotation1.minRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

        x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.rotation1#maxRot"));
        self.rotation1.maxRot = {};
        self.rotation1.maxRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.rotation1.maxRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.rotation1.maxRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

        self.rotation1.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotation1#rotTime"), 2)*1000;
        self.rotation1.touchRotLimit = Utils.degToRad(Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotation1#touchRotLimit"), 10));
    end;
	local rotationNode2 = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.rotation2#index"));
    if rotationNode2 ~= nil then
        self.rotation2 = {};
        self.rotation2.node = rotationNode2;
        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.rotation2#minRot"));
        self.rotation2.minRot = {};
        self.rotation2.minRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.rotation2.minRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.rotation2.minRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

        x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.rotation2#maxRot"));
        self.rotation2.maxRot = {};
        self.rotation2.maxRot[1] = Utils.degToRad(Utils.getNoNil(x, 0));
        self.rotation2.maxRot[2] = Utils.degToRad(Utils.getNoNil(y, 0));
        self.rotation2.maxRot[3] = Utils.degToRad(Utils.getNoNil(z, 0));

        self.rotation2.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotation2#rotTime"), 2)*1000;
        self.rotation2.touchRotLimit = Utils.degToRad(Utils.getNoNil(getXMLString(xmlFile, "vehicle.rotation2#touchRotLimit"), 10));
    end;	

	self.numAttachers = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.Attachers#count"), 0);
	self.Attacher = {};
	self.attacherLevel = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.Attachers#index"));
	self.ulMode = 1;
	self.ulRef = {{"links",false,{5,0,0}},{"hinten",false,{0,0,-5}},{"rechts",false,{-5,0,0}}};	
	for i=1, self.numAttachers do
	 self.Attacher[i] = {};
	 local partnamei = string.format("vehicle.Attachers.objectAttacher".."%d",i);
	 self.Attacher[i].object = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, partnamei .. "#index"));
	 setRigidBodyType(self.Attacher[i].coll,"none")
	 self.Attacher[i].attachedObject = nil;
	 self.Attacher[i].objectInRange = nil;
	end;

end;

function d47:getSaveAttributesAndNodes(nodeIdent)
    for i=1, self.numAttachers do
        ObjectDetachd47(self,i)
    end;
    
   return nil, nil;
end;


function d47:delete()
	for i=1, self.numAttachers do
		ObjectDetachd47(self,i)
	end;
end;

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

function d47:keyEvent(unicode, sym, modifier, isDown)
	if sym == Input.KEY_KP_8 then
		self.rotation1Max = isDown;
	end;
	if sym == Input.KEY_KP_5 then
		self.rotation1Min = isDown;
	end;
	if sym == Input.KEY_KP_7 then
		self.rotation2Max = isDown;
	end;
	if sym == Input.KEY_KP_4 then
		self.rotation2Min = isDown;
	end;
	
	if isDown and sym == Input.KEY_u then
		if self.ulMode == 3 then
		  self.ulMode = 0
		end;
		self.ulMode = self.ulMode + 1
	end;
end;

function d47:update(dt)

	local doRotate = self.rotation1Max or self.rotation1Min 
	if self.rotation1 ~= nil and doRotate then
        local x, y, z = getRotation(self.rotation1.node);
        local rot = {x,y,z};
        local newRot = Utils.getMovedLimitedValues(rot, self.rotation1.maxRot, self.rotation1.minRot, 3, self.rotation1.rotTime, dt, not self.rotation1Max);
        setRotation(self.rotation1.node, unpack(newRot));
    end;
	
	local doRotate = self.rotation2Max or self.rotation2Min 
	if self.rotation2 ~= nil and doRotate then
        local x, y, z = getRotation(self.rotation2.node);
        local rot = {x,y,z};
        local newRot = Utils.getMovedLimitedValues(rot, self.rotation2.maxRot, self.rotation2.minRot, 3, self.rotation2.rotTime, dt, not self.rotation2Max);
        setRotation(self.rotation2.node, unpack(newRot));
    end;
			

	if self:getIsActiveForInput() then
		if InputBinding.isPressed(InputBinding.d47DETACH) then
			-- décrochage
			for i=1, self.numAttachers do
			ObjectDetachd47(self,i)
			end;
		end;

		if InputBinding.isPressed(InputBinding.d47ATTACH) then
			-- détection ballot
			for i=1, self.numAttachers do
				nearest, index = ObjectInRanged47(self,i);
				self.Attacher[i].objectInRange = nearest;
				-- accrochage
				ObjectAttachd47(self,i)
			end;
		end;
	end;
end;

function d47:draw()
	g_currentMission:addExtraPrintText(string.format("Klawisz NUM /: Ballen aufladen"));
	g_currentMission:addExtraPrintText(string.format("Klawisz NUM *: Ballen entladen"));

	--g_currentMission:addHelpButtonText("Zbierz snopki", InputBinding.d47ATTACH);
	--g_currentMission:addHelpButtonText("Rozladuj snopki", InputBinding.d47ATTACH);
	g_currentMission:addExtraPrintText(string.format("Klawisz U: Entladen nach (%s)", self.ulRef[self.ulMode][1]));
	g_currentMission:addExtraPrintText(string.format("Klawisz NUM 7/NUM 4: Bordwand rechts auf/zu"));
	g_currentMission:addExtraPrintText(string.format("Klawisz NUM 8/NUM 5: Bordwand links auf/zu"));
end;

function ObjectInRanged47(self,k)
	--renderText(0.632, 0.225, 0.05, string.format("in range"));
	local nearestObject
	local itemNode
	local index 
	local nearestDistance = 8;
	local objectCopy = self.Attacher[k].object;	
	local px, py, pz = getWorldTranslation(objectCopy);
	for index, item in pairs(g_currentMission.itemsToSave) do
	    itemNode = item.item.nodeId;
	    if getParent(item.item.nodeId) == getRootNode() then
			if getUserAttribute(itemNode, "isStrawbale") or getUserAttribute(itemNode, "isHaybale") then
				local vx, vy, vz = getWorldTranslation(itemNode);
				local distance = Utils.vector3Length(px-vx, py-vy, pz-vz);
				if distance < nearestDistance then
					index = index;
					nearestObject = itemNode
					nearestDistance = distance
				end;
			end;
		end;
	end;
	return nearestObject, index
end;

function ObjectAttachd47(self,k)
	if self.Attacher[k].objectInRange ~= nil then
		if self.Attacher[k].attachedObject == nil then
			setRigidBodyType(self.Attacher[k].objectInRange,"none");
			local x,y,z = getWorldRotation(self.Attacher[k].objectInRange);		
			link(self.Attacher[k].object,self.Attacher[k].objectInRange);
			setRotation(self.Attacher[k].objectInRange, 0,0,0);
			setTranslation(self.Attacher[k].objectInRange, 0,0,0)
			self.Attacher[k].attachedObject = self.Attacher[k].objectInRange;
			self.Attacher[k].objectInRange = nil;
		end;
	end;
end;

function ObjectDetachd47(self,k)
	if self.Attacher[k].attachedObject ~= nil then			
		if not self.ulRef[self.ulMode][2] then
			local x,y,z = getWorldTranslation(self.Attacher[k].attachedObject)
			local rx,ry,rz = getWorldRotation(self.Attacher[k].attachedObject)
			local nx,ny,nz = getWorldTranslation(self.attacherLevel);
			local tx,ty,tz = unpack(self.ulRef[self.ulMode][3]);
			local x = x + tx
			local y = y + ty
			local z = z + tz
			local tH = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, x, 0, z);
			local relHeight = ny - tH
			local root = getRootNode()
			setRigidBodyType(self.Attacher[k].attachedObject,"Dynamic")
			setTranslation(self.Attacher[k].attachedObject,x,(y - relHeight),z)
			setRotation(self.Attacher[k].attachedObject,rx,ry,rz)
			link(root,self.Attacher[k].attachedObject)
			self.Attacher[k].attachedObject = nil;
		else
			---[[ --Custom unloading chunk.  If you break the game with this and can't fix it, remove a dash from this line to deactivate it.
			--print(self.ulRef[self.ulMode][3]);
			-- End of custom unloading chunk. Just leave this line alone.]]
		end;
	end;
end;