--
-- Kverneland 4028 
-- Specialization for a mower.
--
-- author  	Henly20 
-- date  	19-12-2010.
-- www.ls-uk.info
-- ALL RIGHTS RESERVED
  
TaarupMowerCut = {};
  
function TaarupMowerCut.prerequisitesPresent(specializations)
    return true;
end;
  
function TaarupMowerCut:load(xmlFile)

    self.setIsTurnedOn = SpecializationUtil.callSpecializationsFunction("setIsTurnedOn");
	
    self.groundReferenceThreshold = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.groundReferenceNode#threshold"), 0.5);
    self.groundReferenceNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.groundReferenceNode#index"));
    if self.groundReferenceNode == nil then
        self.groundReferenceNode = self.components[2].node;
    end;
 
      self.mowerCutAreasSend = {};
      self.mowerCutAreas = {}
      local i=0;
      while true do
          local areaKey = string.format("vehicle.mowerCutAreas.mowerCutArea(%d)", i);
          if not hasXMLProperty(xmlFile, areaKey) then
              break;
          end
          local area = {};
          if self:loadAreaFromXML(area, xmlFile, areaKey) then
              area.dropWindrow = Utils.getNoNil(getXMLBool(xmlFile, areaKey .. "#dropWindrow"), true);
              area.dropArea = getXMLInt(xmlFile, areaKey .. "#dropArea");
              if area.dropArea ~= nil and self.mowerWindrowDropAreas[area.dropArea] == nil then
                  area.dropArea = nil;
              end
              table.insert(self.mowerCutAreas, area);
              table.insert(self.mowerCutAreasSend, {});
          end
          i = i + 1;
      end
  
      -- fallback: load in cutting areas
      if table.getn(self.mowerCutAreas) == 0 then
          for _, cuttingArea in pairs(self.cuttingAreas) do
              cuttingArea.dropWindrow = true;
              table.insert(self.mowerCutAreas, cuttingArea);
              table.insert(self.mowerCutAreasSend, {});
          end
      end 

      self.isTurnedOn = false;
      self.wasToFast = false;
      
      self.mowerGroundFlag = self.nextDirtyFlag;
      self.nextDirtyFlag = self.mowerGroundFlag*2;

	  self.mowerParticleSystemsRight = {};
      local i = 0;
      while true do
        local namei = string.format("vehicle.mowerParticleSystemsRight.mowerParticleSystemsRight(%d)", i);
		local nodei = Utils.indexToObject(self.components, getXMLString(xmlFile, namei .. "#index"));
		if nodei == nil then
			break;
		end; 
        Utils.loadParticleSystem(xmlFile, self.mowerParticleSystemsRight, namei, nodei, false, nil, self.baseDirectory)		
		i = i +1;		
      end;
	  
	  self.mowerParticleSystemsLeft = {};
      local i = 0;
      while true do
        local namei = string.format("vehicle.mowerParticleSystemsLeft.mowerParticleSystemsLeft(%d)", i);
		local nodei = Utils.indexToObject(self.components, getXMLString(xmlFile, namei .. "#index"));
		if nodei == nil then
			break;
		end; 
        Utils.loadParticleSystem(xmlFile, self.mowerParticleSystemsLeft, namei, nodei, false, nil, self.baseDirectory)		
		i = i +1;		
      end;	  
 

    self.printWarningTime1 = 0;
	self.lastArea = 0;
	self.lastAreaBiggerZero = self.lastArea > 0;

end;

function TaarupMowerCut:delete()
	if self.mowerParticleSystemsRight ~= nil then
		Utils.deleteParticleSystem(self.mowerParticleSystemsRight);
	end;
	if self.mowerParticleSystemsLeft ~= nil then	
		Utils.deleteParticleSystem(self.mowerParticleSystemsLeft);
	end;

end;
  
function TaarupMowerCut:readStream(streamId, connection)
	  
    local turnedOn = streamReadBool(streamId);
    self:setIsTurnedOn(turnedOn, true);
	
	self.lastAreaBiggerZero = streamReadBool(streamId);

end;
  
function TaarupMowerCut:writeStream(streamId, connection)

    streamWriteBool(streamId, self.isTurnedOn);
	
	streamWriteBool(streamId, self.lastAreaBiggerZero);

end;
  
function TaarupMowerCut:readUpdateStream(streamId, timestamp, connection)
	if connection:getIsServer() then
		self.lastAreaBiggerZero = streamReadBool(streamId);

	end;
end;
  
function TaarupMowerCut:writeUpdateStream(streamId, connection, dirtyMask)
	if not connection:getIsServer() then
		streamWriteBool(streamId, self.lastAreaBiggerZero);
	end;
end;
  
function TaarupMowerCut:mouseEvent(posX, posY, isDown, isUp, button)
end;
  
function TaarupMowerCut:keyEvent(unicode, sym, modifier, isDown)

end;
  
function TaarupMowerCut:update(dt)
  
    if self:getIsActiveForInput() then

    end;
end;
  
function TaarupMowerCut:updateTick(dt)
		
    self.wasToFast = false;
	self.lastArea = 0;	
    if self:getIsActive() then

	
		if not self.attacherVehicle.isMotorStarted then
			self.isTurnedOn = false;
		end;
		if self.PTOId then
			self.isTurnedOn = false;
		end;
        if self.isTurnedOn then
			
              local toFast = self:doCheckSpeedLimit() and self.lastSpeed*3600 > 31;
              if not toFast then
                  if self.isServer then
                      local x,y,z = getWorldTranslation(self.groundReferenceNode);
                      local terrainHeight = getTerrainHeightAtWorldPos(g_currentMission.terrainRootNode, x, 0, z);
                      if terrainHeight+self.groundReferenceThreshold >= y then
                          local numAreasSend = 0;
                          local numDropAreas = 0;
                          local areasSend = self.mowerCutAreasSend;
                          for _,area in pairs(self.mowerCutAreas) do
                              if self:getIsAreaActive(area) then
                                  numAreasSend = numAreasSend + 1;
                                  areasSend[numAreasSend].x,_,areasSend[numAreasSend].z = getWorldTranslation(area.start);
                                  areasSend[numAreasSend].x1,_,areasSend[numAreasSend].z1 = getWorldTranslation(area.width);
                                  areasSend[numAreasSend].x2,_,areasSend[numAreasSend].z2 = getWorldTranslation(area.height);
                                  areasSend[numAreasSend].dropWindrow = area.dropWindrow;
                                  areasSend[numAreasSend].dropArea = area.dropArea;
                                  if self.useMowerWindrowDropAreas then
                                      areasSend[numAreasSend].dropWindrow = true;
                                  else
                                      areasSend[numAreasSend].dropArea = nil;
                                  end
                              end
                          end					  				  
						  
                          if numAreasSend > 0 then
                              local numAreasUsed, numDropAreasUsed, pickedUpWindrow = MowerAreaEvent.runLocally(areasSend, numAreasSend, self.mowerWindrowDropAreas, numDropAreas);
		
							self.lastArea = numAreasUsed;
							self.lastAreaBiggerZero = (self.lastArea > 0);
                            if numAreasUsed > 0 or numDropAreasUsed > 0 then
                                g_server:broadcastEvent(MowerAreaEvent:new(areasSend, numAreasUsed, self.mowerWindrowDropAreas, numDropAreas, numDropAreasUsed));
                            end
						end;
                    end;
                end;
            end;

              self.wasToFast = toFast;
  
          else

          end;	
      end;

	for i, jointDesc in pairs(self.componentJoints) do
	   setJointFrame(self.componentJoints[i].jointIndex, 0, self.componentJoints[i].jointNode);
	end;
	
end;
  
function TaarupMowerCut:draw()
    if self.isClient then
		if not self.PTOId then
			if self.isTurnedOn then
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_off_OBJECT"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA);
			else
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_on_OBJECT"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA);
			end;
		end;
		if self.printWarningTime1 > self.time then
			g_currentMission:addWarning(g_i18n:getText("turnON_Error"), 0.018, 0.033);
		end;
    end;
end;
  
function TaarupMowerCut:onDetach()
      if self.deactivateOnDetach then
          TaarupMowerCut.onDeactivate(self);
      else
 
      end;
end;

function TaarupMowerCut:onAttach(attacherVehicle)

end;

function TaarupMowerCut:onLeave()
	if self.deactivateOnLeave then
          TaarupMowerCut.onDeactivate(self);
      else

      end;
	if self.mowerParticleSystemsRight ~= nil then
		Utils.setEmittingState(self.mowerParticleSystemsRight, false);
	end; 
	if self.mowerParticleSystemsLeft ~= nil then
		Utils.setEmittingState(self.mowerParticleSystemsLeft, false);
	end; 	
end;
  
function TaarupMowerCut:onDeactivate()
 
	self:setIsTurnedOn(false, true);
	
end;

function TaarupMowerCut:validateAttacherJoint(implement, jointDesc, dt)
    return true;
end;
  
function TaarupMowerCut:setIsTurnedOn(turnedOn, noEventSend)
      SetTurnedOnEvent.sendEvent(self, turnedOn, noEventSend)
      self.isTurnedOn = turnedOn;
end;


