
---xyzspain 2014




Wrapper = {};

function Wrapper.prerequisitesPresent(specializations)
   return true;
end;

function Wrapper:load(xmlFile)


	self.setWrappingMode = SpecializationUtil.callSpecializationsFunction("setWrappingMode");
	 self.wrappingMode=false;
	  self.baleInTable=false;
	 
-- Wrapper
-- Specialization for Wrapper mod
--
-- @author  JoXXer
-- @date  2011/01/09
	 
	 -- Wickler
-- Specialization zum automatischen wickeln
--
-- @author  teiger
-- @date  14/10/2011

	self.setWrapping = SpecializationUtil.callSpecializationsFunction("setWrapping");


	self.setBalesVisibility = SpecializationUtil.callSpecializationsFunction("setBalesVisibility");
	self.setResetActiveBale = SpecializationUtil.callSpecializationsFunction("setResetActiveBale");

	
	-- Static Bales --
	self.numStaticBales = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.staticBales#count"), 0);	
	self.staticBales = {};
	for i=1, self.numStaticBales do
        local baleNamei = string.format("vehicle.staticBales.staticBale" .. "%d", i);
        self.staticBales[i] = Utils.indexToObject(self.components, getXMLString(xmlFile, baleNamei .. "#index"));
    end;
	
	
	
	-- Bale wrappingTable attacher --
	self.searchTableBales = Wrapper.searchTableBales;
	self.attachTableObjects = Wrapper.attachTableObjects;
	self.detachTableObjects = Wrapper.detachTableObjects;
	
	
	self.isBaleInTableRange = Wrapper.isBaleInTableRange;
	self.tablePlace = {};
	self.tablePlace.node1 = Utils.indexToObject(self.components, getXMLString(xmlFile,"vehicle.Wrappingtable#castPoint1"));		
	self.tablePlace.node2 = Utils.indexToObject(self.components, getXMLString(xmlFile,"vehicle.Wrappingtable#castPoint2"));
	self.tablePlace.attacherNode = Utils.indexToObject(self.components, Utils.getNoNil(getXMLString(xmlFile,"vehicle.Wrappingtable#attacherNode"),"0>12|0"));
	self.tablePlace.highOffset = Utils.getNoNil(getXMLFloat(xmlFile,"vehicle.Wrappingtable#highOffset"),4);	
	self.AttachedTableObjects = {};
	
	self.allowTableAttachment = true;
	self.balesOnTableAttached = false;
	self.baleCanBeWrapped = false;
	
	-- Animations --
	
	self.WrappingAnimation = getXMLString(xmlFile, "vehicle.WrappingTableWrapping#animationName");
	
	
	
	self.isReadyToUnload = false;
	
	self.isUnloading = false;
	self.isWrapping = false;
	
	 self.isReadyToLoad = false;
	self.isBaleVisible = false;
	self.resetActiveBale = false;
	self.baleActive = 1;
	self.usedFruitType = 0;


   self.bales = {};
   
   self.baleAnimRoot = Utils.getNoNil(Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.baleWrapperAnimation#node")), "0>12|0");

   
   ------------------------------------attach bale in range error---------------------
   
	self.hayBale = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.hayBale#index"));	
	
	setVisibility(self.hayBale, false);

	self.strawBale = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.strawBale#index"));
	 
	setVisibility(self.strawBale, false);

	self.select=false;
	

	 
	 
end;

function Wrapper:delete()
	
end;



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

function Wrapper:keyEvent(unicode, sym, modifier, isDown)

end;



function Wrapper:getSaveAttributesAndNodes(nodeIdent)

end;

function Wrapper:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
	if not resetVehicles then
	
	
	end;
    return BaseMission.VEHICLE_LOAD_OK;
end;

function Wrapper:update(dt)
	
	
	 if self.attacherVehicle ~= nil then
	

				if InputBinding.hasEvent(InputBinding.WRAPPING) then
					 self:setWrappingMode(not self.wrappingMode);
				 end;
		
					
			 if self.isReadyToLoad  then
				 self:searchTableBales();
				 if self.baleCanBeWrapped then
					 self.isWrapping = true;
					 self:setWrapping(true);
				end;
			 end;
		
			
		
		
			
		if  self.wrappingMode then
				 if not self.isReadyToUnload then
					 self.isReadyToLoad = true;
					--- renderText(0.1, 0.16, 0.03," self.baleCanBeWrapped = true  ");
				 elseif self.isReadyToUnload then
				 self.isReadyToLoad = false;
				--- renderText(0.1, 0.14, 0.03," self.baleCanBeWrapped false  ");
				 end;
		else
				self.isReadyToUnload= false;
		 end;

			
	end;  ---attacher
	
	
	
		
end;




function Wrapper:setWrappingMode(wrappingMode)
	WrappingEvent.sendEvent(self, wrappingMode, noEventSend);
	self.wrappingMode = wrappingMode;
end;




	
function Wrapper:updateTick(dt)

	-- for k,anim in pairs(self.animationParts) do
		-- print(tostring(k) .. "   " .. tostring(anim.currentPosition))
	-- end

	-- if self.animationParts[1].currentPosition < 60 then --reset the loops, otherwise it will result in overflow of animation counters after 40+ bales
		
		-- self.animationParts[5].inputDone = true;
		-- setAnimTrackTime(self.animationParts[5].animCharSet, self.animationParts[5].clip, timeInput);
		-- setAnimTrackSpeedScale(self.animationParts[5].animCharSet, self.animationParts[5].clip, 0);
		
		-- self.animationParts[6].inputDone = true;
		-- setAnimTrackTime(self.animationParts[6].animCharSet, self.animationParts[6].clip, timeInput);
		-- setAnimTrackSpeedScale(self.animationParts[6].animCharSet, self.animationParts[6].clip, 0);
	-- end;
		
	
	
	if self:getRealAnimationTime(self.WrappingAnimation)>= 28000 and self.isWrapping then

		
		self.isWrapping = false;
		self:setWrapping(false);
		self.isReadyToUnload = true;
		self:setBalesVisibility(not self.isBaleVisible);
		self:setResetActiveBale(not self.resetActiveBale);
		
	end;
	
	
	
	if self.isWrapping then
		
			if self:getRealAnimationTime(self.WrappingAnimation) > 0 and self:getRealAnimationTime(self.WrappingAnimation) <= 25000 then
			
				self:setAnimationTime(3, 1);
				
			end;
			if self:getRealAnimationTime(self.WrappingAnimation) > 0 and self:getRealAnimationTime(self.WrappingAnimation) <= 27500 then
			
				self:setAnimationTime(4, 1);
			
			end;	
		
		if self:getRealAnimationTime(self.WrappingAnimation) >= 1026 and getVisibility(self.staticBales[1]) == false and self.baleActive == 1 then
			self:setBalesVisibility(not self.isBaleVisible);
		elseif self:getRealAnimationTime(self.WrappingAnimation) >= 2500 and getVisibility(self.staticBales[2]) == false and self.baleActive == 2 then
			self:setBalesVisibility(not self.isBaleVisible);
		elseif self:getRealAnimationTime(self.WrappingAnimation) >= 5000 and getVisibility(self.staticBales[3]) == false and self.baleActive == 3 then
			self:setBalesVisibility(not self.isBaleVisible);
		elseif self:getRealAnimationTime(self.WrappingAnimation) >= 7500 and getVisibility(self.staticBales[4]) == false and  self.baleActive == 4 then
			self:setBalesVisibility(not self.isBaleVisible);
		elseif self:getRealAnimationTime(self.WrappingAnimation) >= 10000 and getVisibility(self.staticBales[5]) == false and  self.baleActive == 5 then
			self:setBalesVisibility(not self.isBaleVisible);
		elseif self:getRealAnimationTime(self.WrappingAnimation) >= 12500 and getVisibility(self.staticBales[6]) == false and self.baleActive == 6 then
			self:setBalesVisibility(not self.isBaleVisible);
		elseif self:getRealAnimationTime(self.WrappingAnimation) >= 15000 and getVisibility(self.staticBales[7]) == false and  self.baleActive == 7 then
			self:setBalesVisibility(not self.isBaleVisible);
		elseif self:getRealAnimationTime(self.WrappingAnimation) >= 17500 and getVisibility(self.staticBales[8]) == false and self.baleActive == 8 then
			self:setBalesVisibility(not self.isBaleVisible);
		elseif self:getRealAnimationTime(self.WrappingAnimation) >= 20000 and getVisibility(self.staticBales[9]) == false and self.baleActive == 9 then
			self:setBalesVisibility(not self.isBaleVisible);
		elseif self:getRealAnimationTime(self.WrappingAnimation) >= 22500 and getVisibility(self.staticBales[10]) == false and self.baleActive == 10 then
			self:setBalesVisibility(not self.isBaleVisible);
		elseif self:getRealAnimationTime(self.WrappingAnimation) >= 25000 and getVisibility(self.staticBales[11]) == false and self.baleActive == 11 then
			self:setBalesVisibility(not self.isBaleVisible);
				self:setAnimationTime(3, 0);
		
		end;
		
		--here starts new code for rotation
		
		local aTime = self:getRealAnimationTime(self.WrappingAnimation);
		
		if aTime < 25000 and aTime > 5000 then
			local baleRot = (aTime-5000)/20000/2.2*2*math.pi
		
			setRotation(self.hayBale,0,0,baleRot)
			setRotation(self.strawBale,0,0,baleRot)
			for k,bale in pairs(self.staticBales) do
				local rot = (aTime%2500-2500)/2500/22*2*math.pi
				setRotation(bale,0,math.pi/2,rot)
			end	
		end;
		
		--end of rotation
		
		if self:getRealAnimationTime(self.WrappingAnimation) >= 27500 then	
			
			self:setAnimationTime(4, 0);
				
		end;
		
			self.select = true;
					 if self.usedFruitType == Fillable.FILLTYPE_DRYGRASS_WINDROW or self.usedFruitType == Fillable.FILLTYPE_GRASS_WINDROW then
						self.select = false;
					end
							
							if  self.select then
									setVisibility(self.strawBale, true);
									setVisibility(self.hayBale, false);
							else
								setVisibility(self.hayBale, true);
								setVisibility(self.strawBale, false);
							end; 
	else
	
	
	setVisibility(self.hayBale, false);
	setVisibility(self.strawBale, false);
	end;
	
end;
---tableattachings--
function Wrapper:isBaleInTableRange(node1,node2,Yoffset,Bale)
	local Xmax, Ymax, Zmax = getWorldTranslation(node1);
		  Xmax, Ymax, Zmax = worldToLocal(self.tablePlace.attacherNode,Xmax, Ymax, Zmax);
		  
	local Xmin, Ymin, Zmin = getWorldTranslation(node2);	
		  Xmin, Ymin, Zmin = worldToLocal(self.tablePlace.attacherNode,Xmin, Ymin, Zmin);
	
	local Xt, Yt, Zt = getWorldTranslation(Bale);
		  Xt, Yt, Zt = worldToLocal(self.tablePlace.attacherNode,Xt, Yt, Zt);
		
	if (Xt < math.max(Xmax,Xmin) and Xt > math.min(Xmax,Xmin)) and (Zt < math.max(Zmax,Zmin) and Zt > math.min(Zmax,Zmin)) and (Yt<= ((Ymax+Ymin)/2)+Yoffset and Yt>= (Ymax+Ymin)/2) then
		return true;
		
	else
		return false;
	end;
end;

function Wrapper:searchTableBales()
	for index,item in pairs(g_currentMission.itemsToSave) do
		if item.item:isa(Bale) then 
			if item.item.isAttached == nil then
				local isInRange = self:isBaleInTableRange(self.tablePlace.node1,self.tablePlace.node2,self.tablePlace.highOffset,item.item.nodeId);
				if isInRange and self.isWrapping and self.wrappingMode then
					local baleObject = item.item;
					if baleObject ~= nil and baleObject:isa(Bale) then
						self.usedFruitType = baleObject.fillType;
						self.usedFillLevel = baleObject.fillLevel;
						-- baleObject:delete();
					end;
					self.baleCanBeWrapped = false;
				elseif isInRange and self.wrappingMode  then
					self.baleCanBeWrapped = isInRange;
					self.baleInRange = item.item;
				elseif isInRange and not self.wrappingMode then
					self.baleInTable = isInRange;
					self.baleInRange = item.item;	
					
				elseif not isInRange and self.baleInRange == item.item then
					self.baleCanBeWrapped = isInRange;
					self.baleInTable = isInRange;
					self.baleInRange = nil;
				end;
			end;
		end;
	end;
end;
-- function Wrapper:attachTableObjects(object,baleT)
	-- local attachedobject = {};
	-- attachedobject.object = object;
	-- if self.isServer then
		-- attachedobject.AT = createTransformGroup("AT");
		-- link(self.tablePlace.attacherNode,attachedobject.AT);
		
		-- attachedobject.objectMass = getMass(object);
		-- setMass(object,attachedobject.objectMass*0.01);
		
		-- self:tableOrientJoint(object,attachedobject.AT);

		-- local constr = JointConstructor:new();					
		-- constr:setActors(self.tablePlace.attacherNode, object);
		-- constr:setJointTransforms(attachedobject.AT,  object);
		-- for i=1, 3 do
			-- constr:setTranslationLimit(i-1, true, 0, 0);
			-- constr:setRotationLimit(i-1,0,0);
		-- end;
		-- attachedobject.JointIndex = constr:finalize();
		
		-- if baleT ~= nil then
			-- attachedobject.baleT = baleT;
			-- baleT.isAttached = true;
			-- renderText(0.1, 0.16, 0.03," baleT.isAttached = true  ");
		-- end;
	-- end;

	-- table.insert(self.AttachedTableObjects, attachedobject);
	-- return true;
-- end;

-- function Wrapper:detachTableObjects()
	-- if self.isServer then
		-- for k,v in pairs(self.AttachedTableObjects) do
			-- removeJoint(v.JointIndex);
			-- delete(v.AT);
			-- v.JointIndex = nil;
			-- setMass(v.object,v.objectMass);
			-- if v.baleT ~= nil then
				-- v.baleT.isAttached = nil;
			-- end;
		-- end;
	-- end;
		-- renderText(0.1, 0.18, 0.03," self.balesOnTableAttached = false  ");
	-- self.AttachedTableObjects = nil;
	-- self.AttachedTableObjects = {};
	-- self.balesOnTableAttached = false;
-- end;
function Wrapper:setBalesVisibility(baleVisibility, noEventSend)
	if baleVisibility ~= self.isBaleVisible then
		if noEventSend == nil or noEventSend == false then
			if g_server ~= nil then
				g_server:broadcastEvent(SetBalesEvent:new(self, baleVisibility), nil, nil, self);
			else
				g_client:getServerConnection():sendEvent(SetBalesEvent:new(self, baleVisibility));
			end;
		end;
		self.isBaleVisibile = baleVisibility;
		if self.baleActive ~= 12 then
			setVisibility(self.staticBales[self.baleActive], baleVisibility);
		end;
		if self.baleActive ~= 1 then
			setVisibility(self.staticBales[self.baleActive-1], not baleVisibility);
		end;
		--print(string.format("Should set bale" .. "%d" .. " visible in setBalesVisibility", self.baleActive));
		self.baleActive = self.baleActive+1;
	end;
end;



function Wrapper:draw()
-- if not self.wrappingMode then
			-- g_currentMission:addHelpButtonText(g_i18n:getText("Wrapper_7"), InputBinding.WRAPPING);
		-- else
			-- g_currentMission:addHelpButtonText(g_i18n:getText("Wrapper_8"), InputBinding.WRAPPING);
		-- end;
	
		
end;


function Wrapper:setWrapping(isWrapping,noEventSend)
	SetWrappingEvent.sendEvent(self, isWrapping, noEventSend);
	-- Play wrapping animation --
	if self.WrappingAnimation ~= nil and self.playAnimation ~= nil then
		self:playAnimation(self.WrappingAnimation, 1, nil, true);
		self.isReadyToLoad = false;
		---renderText(0.1, 0.12, 0.02,"self.isReadyToLoad = false self:playAnimation(self.WrappingAnimation, 1, nil, true); ");
	end;
end;

function Wrapper:setResetActiveBale(activeBaleReset, noEventSend)
	SetActiveBaleEvent.sendEvent(self, activeBaleReset, noEventSend);
	if activeBaleReset then
		self.baleActive = 1;
	end;
end;

function Wrapper:readStream(streamId, connection)
    
	self:setWrapping(streamReadBool(streamId), true);
	self:setUnloading(streamReadBool(streamId), true);
	
	self:setBalesVisibility(streamReadBool(streamId), true);
	self:setResetActiveBale(streamReadBool(streamId), true);

end;

function Wrapper:writeStream(streamId, connection)
   
	streamWriteBool(streamId, self.isWrapping);

	streamWriteBool(streamId, self.isUnloading);
	streamWriteBool(streamId, self.isBaleVisible);
	streamWriteBool(streamId, self.resetActiveBale);
	
	
end;









