-- NI Modding
--
-- author  	Henly20 
-- date  	03-03-2013.
-- ni_modding@hotmail.com
-- http://nimodding.wordpress.com
  
KevCondAS = {};
  
function KevCondAS.prerequisitesPresent(specializations)
 	return SpecializationUtil.hasSpecialization(KevMT, specializations);
end;
  
function KevCondAS:load(xmlFile)

	  self.setCondPanel = SpecializationUtil.callSpecializationsFunction("setCondPanel");
	  self.CondPanelAnimation = getXMLString(xmlFile, "vehicle.CondPanel#animationName");
	  self.CondPanel = true;  
	  self.setArmOne = SpecializationUtil.callSpecializationsFunction("setArmOne");
	  self.ArmOneAnimation = getXMLString(xmlFile, "vehicle.armOne#animationName");
	  self.ArmOne = false;	  
      self.setConditionerOn = SpecializationUtil.callSpecializationsFunction("setConditionerOn");
	  self.conditionerNode = {};
	  self.conditionerNode.node  = Utils.indexToObject(self.components,getXMLString(xmlFile, "vehicle.conditionerNode#index"));

      self.groundReferenceThreshold = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.groundReferenceNode#threshold"), 0.2);
      self.groundReferenceNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.groundReferenceNode#index"));
      if self.groundReferenceNode == nil then
          self.groundReferenceNode = self.components[1].node;
      end;
  
      local numWindrowerDropAreas = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.windrowerDropAreas#count"), 0);
      if numWindrowerDropAreas == 0 then
          print("Warning: No drop areas specified in '"..self.configFileName.."'");
      else
          if numWindrowerDropAreas ~= 1 and numWindrowerDropAreas ~= table.getn(self.cuttingAreas) then
              print("Warning: Number of cutting areas and drop areas should be equal in '"..self.configFileName.."'");
          end;
      end;
      self.windrowerDropAreas = {}
      for i=1, numWindrowerDropAreas do
          self.windrowerDropAreas[i] = {};
          local areanamei = string.format("vehicle.windrowerDropAreas.windrowerDropArea%d", i);
          self.windrowerDropAreas[i].start = Utils.indexToObject(self.components, getXMLString(xmlFile, areanamei .. "#startIndex"));
          self.windrowerDropAreas[i].width = Utils.indexToObject(self.components, getXMLString(xmlFile, areanamei .. "#widthIndex"));
          self.windrowerDropAreas[i].height = Utils.indexToObject(self.components, getXMLString(xmlFile, areanamei .. "#heightIndex"));
      end;
  
      local numCuttingAreas = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.cuttingAreas#count"), 0);
      self.accumulatedCuttingAreaValues = {};
      for i=1, numCuttingAreas do
          local areanamei = string.format("vehicle.cuttingAreas.cuttingArea%d", i);
          self.cuttingAreas[i].foldMinLimit = Utils.getNoNil(getXMLFloat(xmlFile, areanamei .. "#foldMinLimit"), 0);
          self.cuttingAreas[i].foldMaxLimit = Utils.getNoNil(getXMLFloat(xmlFile, areanamei .. "#foldMaxLimit"), 1);
          self.accumulatedCuttingAreaValues[i] = 0;
      end;
	  self.isTurnedOn = false;
	  self.isConditionerOn = true;
  
      self.windrowerGroundFlag = self.nextDirtyFlag;
      self.nextDirtyFlag = self.windrowerGroundFlag*2;
	  
      self.KevUVScrollParts = {};
      local i = 0;
      while true do
          local key = string.format("vehicle.KevUVScrollParts.KevUVScrollPart(%d)", i);
          if not hasXMLProperty(xmlFile, key) then
              break;
          end;
          local node = Utils.indexToObject(self.components, getXMLString(xmlFile, key.."#index"));
          local speed = Utils.getVectorNFromString(getXMLString(xmlFile, key.."#speed"), 2);
          if node ~= nil and speed then
              table.insert(self.KevUVScrollParts, {node=node, speed=speed});
          end;
          i = i +1;
      end;
	  
	  self.ASParticleSystems = {};
      local i = 0;
      while true do
        local namei = string.format("vehicle.ASParticleSystems.ASParticleSystem(%d)", i);
		local nodei = Utils.indexToObject(self.components, getXMLString(xmlFile, namei .. "#index"));
		if nodei == nil then
			break;
		end; 
        Utils.loadParticleSystem(xmlFile, self.ASParticleSystems, namei, nodei, false, nil, self.baseDirectory)		
		i = i +1;		
      end;
end;
  
function KevCondAS:delete()
	Utils.deleteParticleSystem(self.ASParticleSystems);
  
end;
  
function KevCondAS:mouseEvent(posX, posY, isDown, isUp, button)
end;
  
function KevCondAS:keyEvent(unicode, sym, modifier, isDown)
end;

function KevCondAS:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
	if not resetVehicles then

	end;
    return BaseMission.VEHICLE_LOAD_OK;
end;

function KevCondAS:getSaveAttributesAndNodes(nodeIdent)

end;
  
function KevCondAS:readStream(streamId, connection)
      local isConditionerOn = streamReadBool(streamId);
      self:setConditionerOn(isConditionerOn, true);
      self:setCondPanel(streamReadBool(streamId), true);
      self:setArmOne(streamReadBool(streamId), true);	  
end;
  
function KevCondAS:writeStream(streamId, connection)
      streamWriteBool(streamId, self.isConditionerOn);
      streamWriteBool(streamId, self.CondPanel);
	  streamWriteBool(streamId, self.ArmOne);	  
end;
  
function KevCondAS:readUpdateStream(streamId, timestamp, connection)
end;
  
function KevCondAS:writeUpdateStream(streamId, connection, dirtyMask)
end;
  
function KevCondAS:update(dt)
  
	if not self:getIsActive() then
		if self.conditionerInRange and not self.isArmOneOn then
			if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA3) then
				self:setCondPanel(not self.CondPanel);
			end;
			if not self.CondPanel then
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText("conditionerOn"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA3);
			else
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText("conditionerOff"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA3);
			end;
		end;
	end;
	
	if self:getIsActiveForInput() then
		if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA4) and self.isConditionerOn then
			self:setArmOne(not self.isArmOneOn);
		end;
	end;
end;
  
function KevCondAS:updateTick(dt)

		if g_currentMission.player ~= nil then
			local nearestDistance = 3;
			local vx, vy, vz = getWorldTranslation(g_currentMission.player.rootNode);		
			local px, py, pz = getWorldTranslation(self.conditionerNode.node); 
			local distance = Utils.vector3Length(px-vx, py-vy, pz-vz);	
			if distance < nearestDistance then
				self.conditionerInRange = true; 
			else
				self.conditionerInRange = false; 
			end;
		end;
		
    if self:getIsActive() then
		if self.CondPanel then
			self:setConditionerOn(true);
			else
			self:setConditionerOn(false);
		end;
          if self.isConditionerOn and self.isTurnedOn and not self.isWheelRotOn 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 numDropAreas = table.getn(self.windrowerDropAreas);
                          local numAreas = table.getn(self.cuttingAreas);
                          if numDropAreas > 0 and numAreas > 0 then
                              local sum = 0;
                              local fruitType = FruitUtil.FRUITTYPE_GRASS;
                              local fruitTypeFix = false;
                              local cuttingAreasSend = {};
                              local dropAreasSend = {};
                              for i=1, numAreas do
                                  local cuttingArea = self.cuttingAreas[i];
                                  if self:getIsAreaActive(cuttingArea) then
                                      local x,y,z = getWorldTranslation(cuttingArea.start);
                                      local x1,y1,z1 = getWorldTranslation(cuttingArea.width);
                                      local x2,y2,z2 = getWorldTranslation(cuttingArea.height);
  
                                      table.insert(cuttingAreasSend, {x,z,x1,z1,x2,z2});
                                  end;
                              end;
                              for i=1, numDropAreas do
                                  local dropArea = self.windrowerDropAreas[i];
                                  local dx,dy,dz = getWorldTranslation(dropArea.start);
                                  local dx1,dy1,dz1 = getWorldTranslation(dropArea.width);
                                  local dx2,dy2,dz2 = getWorldTranslation(dropArea.height);
                                  table.insert(dropAreasSend, {dx, dz, dx1, dz1, dx2, dz2});
                              end;
                              if table.getn(cuttingAreasSend) > 0 then
                                  local cuttingAreasSend, dropAreasSend, fruitType, bitType = WindrowAreaEvent.runLocally(cuttingAreasSend, dropAreasSend, self.accumulatedCuttingAreaValues);
                                  if table.getn(cuttingAreasSend) > 0 then
                                      g_server:broadcastEvent(WindrowAreaEvent:new(cuttingAreasSend, dropAreasSend, fruitType, bitType));
                                  end;
                              end;
                          end;
                      end;

              end;
			end;

		for _, part in pairs(self.KevUVScrollParts) do
			if self.isConditionerOn and self.isTurnedOn and self.isArmOneOn then	
				setShaderParameter(part.node, "uvScrollSpeed", part.speed[1], part.speed[2], 0, 0, false);
			else
				setShaderParameter(part.node, "uvScrollSpeed", 0, 0, 0, 0, false);
			end;
		end;
		if self.isTurnedOn and self.movingDirection ~= 0 and self.isArmOneOn and self.lastAreaBiggerZero and not self.isWheelRotOn then
			Utils.setEmittingState(self.ASParticleSystems, true);
		else
			Utils.setEmittingState(self.ASParticleSystems, false);
		end;	
      end;
end;
  
function KevCondAS:draw()
    if self.isClient then
		if self.isConditionerOn then
			if self.isArmOneOn then
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText("raiseAS"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA4);
			else
				g_currentMission:addHelpButtonText(string.format(g_i18n:getText("lowerAS"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA4);
			end;
		end;
	end;
end;
  
function KevCondAS:onDetach()
	if self.ASParticleSystems ~= nil then
		Utils.setEmittingState(self.ASParticleSystems, false);
	end;

	for _, part in pairs(self.KevUVScrollParts) do
		setShaderParameter(part.node, "uvScrollSpeed", 0, 0, 0, 0, false);
	end;
end;
  
function KevCondAS:onLeave()
	if self.deactivateOnLeave then
		KevCondAS.onDeactivate(self);
	else
		KevCondAS.onDeactivateSounds(self);
	end;
	self:setConditionerOn(false, true);
	if self.ASParticleSystems ~= nil then
		Utils.setEmittingState(self.ASParticleSystems, false);
	end; 
end;


  
function KevCondAS:onDeactivate()
	for _, part in pairs(self.KevUVScrollParts) do
		setShaderParameter(part.node, "uvScrollSpeed", 0, 0, 0, 0, false);
	end;
	if self.ASParticleSystems ~= nil then
		Utils.setEmittingState(self.ASParticleSystems, false);
	end; 	
end;
  
function KevCondAS:onDeactivateSounds()

end;
  
function KevCondAS:setConditionerOn(isConditionerOn, noEventSend)
      SetConditionerOnEvent.sendEvent(self, isConditionerOn, noEventSend)
      self.isConditionerOn = isConditionerOn;
end;

function KevCondAS:setCondPanel(isCondPanel,noEventSend)
	SetCondPanelEvent.sendEvent(self, isCondPanel, noEventSend);

	if isCondPanel then
		if self.CondPanelAnimation ~= nil and self.playAnimation ~= nil then
			self:playAnimation(self.CondPanelAnimation, -1, nil, true);
			self.CondPanel = true;
		end;
	else
		if self.CondPanelAnimation ~= nil and self.playAnimation ~= nil then
			self:playAnimation(self.CondPanelAnimation, 1, nil, true);
			self.CondPanel = false;
		end;
	end;	
end;

function KevCondAS:setArmOne(isArmOne,noEventSend)
	SetArmOneEvent.sendEvent(self, isArmOne, noEventSend);
	-- Play ArmOne animation --
	self.isArmOneOn = isArmOne;
	if self.isArmOneOn then
		if self.ArmOneAnimation ~= nil and self.playAnimation ~= nil then
			self:playAnimation(self.ArmOneAnimation, -1, nil, true);
			self.ArmOne = true;
		end;
	else
		if self.ArmOneAnimation ~= nil and self.playAnimation ~= nil then
			self:playAnimation(self.ArmOneAnimation, 1, nil, true);
			self.ArmOne = false;
		end;
	end;	
end;
