-- Lulu88520
-- Script pour la benne leboulch tridem gold
-- Ls-Modteam-France
-- @date  09/06/2014
-- http://www.ls-modteam-france.com

leboulch = {};

function leboulch.prerequisitesPresent(specializations)
	  return SpecializationUtil.hasSpecialization(Fillable, specializations) and SpecializationUtil.hasSpecialization(Trailer, specializations);
end;

function leboulch:load(xmlFile)

	 self.toggleSupport = SpecializationUtil.callSpecializationsFunction("toggleSupport");  
    self.manualSupportAnimation = getXMLString(xmlFile, "vehicle.manualSupport#animationName");
    self.supportRangeIndex = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.manualSupport#rangeIndex"));
    self.isInRangeSupport = false;
    self.isSupportDown = true;	
	
	self.smokeParticleSystems = {};
    local entry = {};
      entry.ps = {};
      Utils.loadParticleSystem(xmlFile, entry.ps, "vehicle.smokeParticleSystem", self.components, false, nil, self.baseDirectory);
      if table.getn(entry.ps) > 0 then
          entry.isActive = false;
          table.insert(self.smokeParticleSystems, entry);
      end
      local i=0;
      while true do
          local baseName = string.format("vehicle.smokeParticleSystems.smokeParticleSystem(%d)", i);
          if not hasXMLProperty(xmlFile, baseName) then
              break;
          end;
          local entry = {};
          entry.ps = {};
          Utils.loadParticleSystem(xmlFile, entry.ps, baseName, self.components, false, nil, self.baseDirectory);
          if table.getn(entry.ps) > 0 then
              entry.isActive = false;
             entry.cuttingArea = i+1;
              table.insert(self.smokeParticleSystems, entry);
          end
          i = i+1;
      end; 	  
	
	
	 self.flexible = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.flexible#index"));
    setVisibility(self.flexible, false);

    self.flexibleDetach = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.flexibleDetach#index"));
    setVisibility(self.flexibleDetach, true);	
	
	 self.doJointSearchCylindered = false;
	self.origMouseControlsAxes = self.mouseControlsAxes;
	self.disaMouseControlsAxes = {};
end;

function leboulch:delete()
for _, entry in ipairs(self.smokeParticleSystems) do
          Utils.deleteParticleSystem(entry.ps);
          entry.isActive = false;
end;
end;

function leboulch:readStream(streamId, connection)	
   local isSupportDown = streamReadBool(streamId);
	self:toggleSupport(isSupportDown, true); 	
end;

function leboulch:writeStream(streamId, connection)
streamWriteBool(streamId, self.isSupportDown);
      
end;

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

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

function leboulch:update(dt)
         if self:getIsActive() then		
		if self.isClient and self:getIsActiveForInput(false) and not self:hasInputConflictWithSelection() then
			-- Show warning about the support being down
			if self.isSupportDown then
				g_currentMission:addWarning(string.format(g_i18n:getText("BJR_SUPPORT_WARNING")), 0.018, 0.033);
			end;
		end;
	end;
         if self.supportRangeIndex then
		-- Manage key events for inrange support --
		if self.isInRangeSupport then
			if InputBinding.hasEvent(InputBinding.LOWER_IMPLEMENT) then
				if self.isSupportDown then
					self:toggleSupport(false);
				else
					self:toggleSupport(true);
				end;
			end;
			-- Display key when in range --
			if self.isSupportDown then
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText("BJR_RAISE_SUPPORT")), InputBinding.LOWER_IMPLEMENT);
			else
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText("BJR_LOWER_SUPPORT")), InputBinding.LOWER_IMPLEMENT);
			end;
		end;
	end;    
	
	
	

end;

function leboulch:updateTick(dt)

 if self.supportRangeIndex then
		if g_currentMission.player ~= nil then
			-- Getting the distance between the player and the support
			local nearestDistance = 1.5; --max distance allowed
			local px, py, pz = getWorldTranslation(self.supportRangeIndex);
			local vx, vy, vz = getWorldTranslation(g_currentMission.player.rootNode);
			local distance = Utils.vector3Length(px-vx, py-vy, pz-vz);
			if distance < nearestDistance then
				self.isInRangeSupport = true;
			else
				self.isInRangeSupport = false;
			end;
		end;
	else
		self.isInRangeSupport = false;
	end; 
  
	
	
	
	if self.isClient then
               for _,ps in pairs(self.smokeParticleSystems) do                  
                  if self.currentFillType == Fillable.FILLTYPE_MANURE and self.fillLevel > 3000 and self.movingDirection == 0 then                       
                      Utils.setEmittingState(ps.ps, true);
                  else
                      Utils.setEmittingState(ps.ps, false);
                  end
               end
 end;
	
	 if self.varTip ~= nil then
		if self.varTip.activeTrailerIdx ~= self.varTip.trailerNr then
			self.mouseControlsAxes = self.disaMouseControlsAxes;
			return;
		else
			self.mouseControlsAxes = self.origMouseControlsAxes;
		end;
	end;
	
	if self.doJointSearchCylindered then
		if self.attacherVehicle ~= nil then
			for k,v in pairs(self.attacherVehicle.attachedImplements) do
				if v.object == self then
					local joint = self.attacherVehicle.attacherJoints[v.jointDescIndex];
					self.vehicleJoint = joint;
					self.doJointSearchCylindered = false;
					break;
				end;
			end;
		end;
		self.doJointSearchCylindered = false;
	end;

	
	 for _, part in pairs(self.movingParts) do
					part.isDirty = true;
		end;
		
		for _, tool in pairs(self.movingTools) do
   tool.isDirty = true;
end;

        if self.vehicleJoint ~= nil then
            setJointFrame(self.vehicleJoint.jointIndex, 1, self.attacherJoint.node);
	end;
end;

function leboulch:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
	local isSupportDown = Utils.getNoNil(getXMLBool(xmlFile, key .. "#isSupportDown"), false);
	self:toggleSupport(isSupportDown);	
	
    return BaseMission.VEHICLE_LOAD_OK;
end;

function leboulch:getSaveAttributesAndNodes(nodeIdent)
    local attributes = 'isSupportDown="' .. tostring(self.isSupportDown) .. '"';
    return attributes, nil;
end;
  
function leboulch:onDetach()
setVisibility(self.flexible, false);
 setVisibility(self.flexibleDetach, true); 
 self.vehicleJoint = nil;
end;

function leboulch:onAttach()
setVisibility(self.flexible, true);
 setVisibility(self.flexibleDetach, false);
self.doJointSearchCylindered = true; 
end;

function leboulch:draw()
end;

function leboulch:toggleSupport(isSupportDown, noEventSend)
	ToggleSupportEvent.sendEvent(self, isSupportDown, noEventSend);	
	
	if not isSupportDown then
		if self.manualSupportAnimation ~= nil and self.playAnimation ~= nil then
			self:playAnimation(self.manualSupportAnimation, -1, nil, true);
		end;
	else
		if self.manualSupportAnimation ~= nil and self.playAnimation ~= nil then
			self:playAnimation(self.manualSupportAnimation, 1, nil, true);
		end;
	end;
	
	self.isSupportDown = isSupportDown;
end;


-- Support event

ToggleSupportEvent = {};
ToggleSupportEvent_mt = Class(ToggleSupportEvent, Event);

InitEventClass(ToggleSupportEvent, "ToggleSupportEvent");

function ToggleSupportEvent:emptyNew()
    local self = Event:new(ToggleSupportEvent_mt);
    return self;
end;

function ToggleSupportEvent:new(vehicle, isSupportDown)
    local self = ToggleSupportEvent:emptyNew()
    self.vehicle = vehicle;
	self.isSupportDown = isSupportDown;
    return self;
end;

function ToggleSupportEvent:readStream(streamId, connection)
    local id = streamReadInt32(streamId);
	self.vehicle = networkGetObject(id);
	self.isSupportDown = streamReadBool(streamId);
    self:run(connection);
end;

function ToggleSupportEvent:writeStream(streamId, connection)
    streamWriteInt32(streamId, networkGetObjectId(self.vehicle));	
	streamWriteBool(streamId, self.isSupportDown);
end;

function ToggleSupportEvent:run(connection)
	self.vehicle:toggleSupport(self.isSupportDown, true);
end;

function ToggleSupportEvent.sendEvent(vehicle, isSupportDown, noEventSend)
	
	if noEventSend == nil or noEventSend == false then
		if g_server ~= nil then
			g_server:broadcastEvent(ToggleSupportEvent:new(vehicle, isSupportDown), nil, nil, vehicle);
		else
			g_client:getServerConnection():sendEvent(ToggleSupportEvent:new(vehicle, isSupportDown));
		end;
	end;
end;


