-- NI Modding
--
-- author  	Henly20 
-- date  	03-11-2012.
-- ni_modding@hotmail.com
-- http://nimodding.wordpress.com
  

McHale_F550 = {};
  
function McHale_F550.prerequisitesPresent(specializations)
      return SpecializationUtil.hasSpecialization(Baler, specializations) and SpecializationUtil.hasSpecialization(ImplementLinks, specializations);
end;
  
function McHale_F550:load(xmlFile)
  
      self.setIsTurnedOn = SpecializationUtil.callSpecializationsFunction("setIsTurnedOn");
 	  self.setVehicleRpmUp = SpecializationUtil.callSpecializationsFunction("setVehicleRpmUp");
	  self.saveMinRpm = 0; 
  
      self.MchaleUVScrollParts = {};
      local i = 0;
      while true do
          local key = string.format("vehicle.MchaleUVScrollParts.balerUVScrollPart(%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.MchaleUVScrollParts, {node=node, speed=speed});
          end;
          i = i +1;
      end;

	  self.getIsAreaActive = Utils.overwrittenFunction(self.getIsAreaActive, McHale_F550.getIsAreaActive);	
	  self.setTransRot = SpecializationUtil.callSpecializationsFunction("setTransRot");
	  self.TransRotAnimation = getXMLString(xmlFile, "vehicle.TransRot#animationName");
	  self.TransRot = false;
  
	self.rotateSpinners = {};
	local i=0;
	while true do
		local baseName = string.format("vehicle.rotateSpinners.node(%d)", i);
		local index = getXMLString(xmlFile, baseName.. "#index");
		local x,y,z = Utils.getVectorFromString(getXMLString(xmlFile, baseName.. "#rotationSpeed"));
		local rotationSpeed = {x,y,z};
		local runOutTime = Utils.getNoNil(getXMLFloat(xmlFile, baseName.. "#runOutTime"), 2)*1000;
		if index == nil or rotationSpeed == nil or runOutTime == nil then
			break;
		end;
		local node = Utils.indexToObject(self.components, index);
		if node ~= nil then
			local entry = {};
			entry.node = node;
			entry.runOutTime = runOutTime;
			entry.rotationSpeedMax = rotationSpeed;
			entry.rotationSpeedMin = {0,0,0};
			entry.rotationSpeedCurrent = {0,0,0};
			table.insert(self.rotateSpinners, entry);
		end;
		i = i+1;
	end;	
	
     self.speedRotatingParts = {};
     local i=0;
     while true do
          local baseName = string.format("vehicle.speedRotatingParts.speedRotatingPart(%d)", i);
          local index = getXMLString(xmlFile, baseName.. "#index");
          if index == nil then
              break;
          end;
          local node = Utils.indexToObject(self.components, index);
          if node ~= nil then
              local entry = {};
              entry.node = node;
              entry.rotationSpeedScale = getXMLFloat(xmlFile, baseName.."#rotationSpeedScale");
              if entry.rotationSpeedScale == nil then
                  entry.rotationSpeedScale = 1.0/Utils.getNoNil(getXMLFloat(xmlFile, baseName.."#radius"), 1);
              end;
  
  
              table.insert(self.speedRotatingParts, entry);
          end;
          i = i+1;
      end;
	
      self.setWheel = SpecializationUtil.callSpecializationsFunction("setWheel");

      self.wheel1 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.pickupWheels#index1"));
      self.wheel2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.pickupWheels#index2"));
      self.wheelId = 0;
	  
      self.printWarningTime = 0;
	  self.allowParticle = false;
	
end;
  
function McHale_F550:delete()

end;
  
function McHale_F550:readStream(streamId, connection)
	self:setTransRot(streamReadBool(streamId), true);
	self:setWheel(streamReadInt8(streamId), true);
end;
  
function McHale_F550:writeStream(streamId, connection)
    streamWriteBool(streamId, self.TransRot);
	streamWriteInt8(streamId, self.wheelId);
end;
  
function McHale_F550:readUpdateStream(streamId, timestamp, connection)
end;
  
function McHale_F550:writeUpdateStream(streamId, connection, dirtyMask)
end;
  
  
function McHale_F550:mouseEvent(posX, posY, isDown, isUp, button)
end;
  
function McHale_F550:keyEvent(unicode, sym, modifier, isDown)
  end;
  
function McHale_F550:update(dt)
  
	if self:getIsActiveForInput() then
		if InputBinding.hasEvent(InputBinding.LOWER_IMPLEMENT) then
			self:setTransRot(not self.isTransRotOn);
		end;
		if InputBinding.isPressed(InputBinding.IMPLEMENT_EXTRA) and self.PTOId then
			self.printWarningTime = self.time + 1500;
		end;
	end;

	
end;
  
function McHale_F550:updateTick(dt)

	if self:getIsActive() then
	if not self.attacherVehicle.isMotorStarted then
      self:setIsTurnedOn(false);
	end;
	if self.PTOId then
		self.isTurnedOn = false;
	end;
		local isKeyEvent = false;	
		if self.isTurnedOn then
 			isKeyEvent = true;	
		else
 			isKeyEvent = false;	
		end;
		self:setVehicleRpmUp(dt, isKeyEvent);	
		for k, spinner in pairs(self.rotateSpinners) do
			local values = Utils.getMovedLimitedValues(spinner.rotationSpeedCurrent, spinner.rotationSpeedMax, spinner.rotationSpeedMin, 3, spinner.runOutTime, dt, not self.isTurnedOn);
			spinner.rotationSpeedCurrent = values;
			rotate(spinner.node, unpack(spinner.rotationSpeedCurrent));
		end;		
		if self.isTurnedOn then

		end;

        for k,v in pairs(self.speedRotatingParts) do
            if self.isTransRotOn and self.movingDirection ~= 0 then
               rotate(v.node, v.rotationSpeedScale * self.lastSpeedReal * self.movingDirection * dt, 0, 0);
            end;                    
        end;
		for _, part in pairs(self.MchaleUVScrollParts) do
			if self.isTurnedOn and self.fillLevel > (self.capacity * 0.92) and self.fillLevel < self.capacity 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 not self.PTOId then
			if self.isTransRotOn then
				setVisibility(self.wheel1, true);
				setVisibility(self.wheel2, false);
			end;
			if not self.isTurnedOn then
				if not self.isTransRotOn then
					setVisibility(self.wheel1, false);
					setVisibility(self.wheel2, true);
				else
					setVisibility(self.wheel1, true);
					setVisibility(self.wheel2, false);
				end;
			end;
		else
			if self.isTransRotOn then
				setVisibility(self.wheel1, true);
				setVisibility(self.wheel2, false);
			else
				setVisibility(self.wheel1, false);
				setVisibility(self.wheel2, true);
			end;
		end;
	end;
end;
  
function McHale_F550:draw()
	if self.isClient then
        if self.isTransRotOn then
            g_currentMission:addHelpButtonText(string.format(g_i18n:getText("TRANSPORT"), self.typeDesc), InputBinding.LOWER_IMPLEMENT);
        else
            g_currentMission:addHelpButtonText(string.format(g_i18n:getText("FIELD"), self.typeDesc), InputBinding.LOWER_IMPLEMENT);
        end;
		if self.printWarningTime > self.time then
			g_currentMission:addWarning(g_i18n:getText("turnON_Error"), 0.018, 0.033);
		end;
	end;
	
end;

function McHale_F550:onDetach()
	if self.deactivateOnDetach then
		McHale_F550.onDeactivate(self);
	else
		McHale_F550.onDeactivateSounds(self);
	end;
	for k, steerable in pairs(g_currentMission.steerables) do
		if self.attacherVehicleCopy == steerable then
			steerable.motor.minRpm = self.saveMinRpm;
			self.attacherVehicleCopy = nil;
		end;
	end;
end;

 function McHale_F550:onAttach(attacherVehicle)
	self.attacherVehicle = attacherVehicle;
	if self.attacherVehicleCopy == nil then
		self.attacherVehicleCopy = self.attacherVehicle;
	end;
	self.saveMinRpm = self.attacherVehicle.motor.minRpm;
end; 

function McHale_F550:onLeave()
	if self.deactivateOnLeave then
		McHale_F550.onDeactivate(self);
	else
		McHale_F550.onDeactivateSounds(self);
	end;

end;
  
function McHale_F550:onDeactivate()
	for _, part in pairs(self.MchaleUVScrollParts) do
		setShaderParameter(part.node, "uvScrollSpeed", 0, 0, 0, 0, false);
	end;
	self.wasToFast = false;
	self.isTurnedOn = false;
	McHale_F550.onDeactivateSounds(self)

end;
  
function McHale_F550:onDeactivateSounds()

end;
  
function McHale_F550:setTransRot(isTransRot,noEventSend)
	SetTransRotEvent.sendEvent(self, isTransRot, noEventSend);
	-- Play TransRot animation --
	self.isTransRotOn = isTransRot;
	if self.isTransRotOn then
		if self.TransRotAnimation ~= nil and self.playAnimation ~= nil then
			self:playAnimation(self.TransRotAnimation, 1, nil, true);
			self.TransRot = true;

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

function McHale_F550:setWheel(wheel, noEventSend)
	PickupWheelEvent.sendEvent(self, wheel, noEventSend);

	setVisibility(self.wheel1, wheel == 1);
	setVisibility(self.wheel2, wheel == 0);
	self.wheelId = wheel;
end;

function McHale_F550:getIsAreaActive(superFunc, area)
    if superFunc ~= nil then
			return superFunc(self, area) and self.isTransRotOn;
    end;
	return self.isTransRotOn;	
end;

function McHale_F550:setVehicleRpmUp(dt, isActive)
	if self.attacherVehicle ~= nil and self.saveMinRpm ~= 0 then
		if dt ~= nil then
			if isActive == true then
				self.attacherVehicle.motor.minRpm = math.max(self.attacherVehicle.motor.minRpm-dt, -1000);
			else
				self.attacherVehicle.motor.minRpm = math.min(self.attacherVehicle.motor.minRpm+dt*2, self.saveMinRpm);
			end;
		else
			self.attacherVehicle.motor.minRpm = self.saveMinRpm;
		end;
		if self.attacherVehicle.isMotorStarted then
			local fuelUsed = 0.00000011*math.abs(self.attacherVehicle.motor.minRpm);
			self.attacherVehicle:setFuelFillLevel(self.attacherVehicle.fuelFillLevel-fuelUsed);
			g_currentMission.missionStats.fuelUsageTotal = g_currentMission.missionStats.fuelUsageTotal + fuelUsed;
			g_currentMission.missionStats.fuelUsageSession = g_currentMission.missionStats.fuelUsageSession + fuelUsed;
		end;
	end;
end;