

fergusonsower = {};

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


function fergusonsower:load(xmlFile)
    self.setIsChange = fergusonsower.setIsChange;	 
    self.setIsTurnedOn = fergusonsower.setIsTurnedOn;	
	self.lastFillLevel = self.fillLevel;
	self.isChange = true;
	self:setIsChange(self.isChange);	
	self.fillLevel = 0;	

 	self.setVehicleRpmUp = SpecializationUtil.callSpecializationsFunction("setVehicleRpmUp");
	self.saveMinRpm = 0; 

	self.spinners = {};
	local count = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.spinners#count"), 0);
    for i=1, count do
		local spinner = {};
        local name = string.format("vehicle.spinners.spinner" .. "%d", i);
	    spinner.node = Utils.indexToObject(self.components, getXMLString(xmlFile, name .. "#index"));
	    spinner.direction = Utils.getNoNil(getXMLInt(xmlFile, name .. "#direction"), 1);
		table.insert(self.spinners, spinner);
    end;
	
    self.printWarningTime = 0;	

    if self.isClient then
		self.fertParticleSystems = {};
		local i = 0;
		while true do
			local namei = string.format("vehicle.fertParticleSystems.fertParticleSystems(%d)", i);
			local nodei = Utils.indexToObject(self.components, getXMLString(xmlFile, namei .. "#index"));
			if nodei == nil then
				break;
			end; 
			Utils.loadParticleSystem(xmlFile, self.fertParticleSystems, namei, nodei, false, nil, self.baseDirectory)		
			i = i +1;		
		end;
		
		self.seedsParticleSystems = {};
			local i = 0;
			while true do
				local namei = string.format("vehicle.seedsParticleSystems.seedsParticleSystems(%d)", i);
				local nodei = Utils.indexToObject(self.components, getXMLString(xmlFile, namei .. "#index"));
				if nodei == nil then
				break;
				end; 
			Utils.loadParticleSystem(xmlFile, self.seedsParticleSystems, namei, nodei, false, nil, self.baseDirectory)		
			i = i +1;		
		 end;
	  
		 local fertiliserSound = getXMLString(xmlFile, "vehicle.fertiliserSound#file");
		 if fertiliserSound ~= nil and fertiliserSound ~= "" then
			fertiliserSound = Utils.getFilename(fertiliserSound, self.baseDirectory);
			self.fertiliserSound = createSample("fertiliserSound");
			self.fertiliserSoundEnabled = false;
			loadSample(self.fertiliserSound, fertiliserSound, false);
			self.fertiliserSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.fertiliserSound#pitchOffset"), 1);
			self.fertiliserSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.fertiliserSound#volume"), 1);
		  end;
      end;
      self.isTurnedOn = false;
	self.overlay = Utils.getFilename("textures/fertilizer_hud.png", self.baseDirectory);
    self.FruitTypeOverlay = Overlay:new("hudPDAControl", self.overlay, g_currentMission.fruitSymbolX, g_currentMission.fruitSymbolY, g_currentMission.fruitSymbolSize, g_currentMission.fruitSymbolSize * (4 / 3));	  
end;


function fergusonsower:delete()
 	Utils.deleteParticleSystem(self.fertParticleSystems);
	Utils.deleteParticleSystem(self.seedsParticleSystems);
	
      if self.fertiliserSound ~= nil then
          delete(self.fertiliserSound);
      end;
end;

function fergusonsower:readStream(streamId, connection)
      local change = streamReadBool(streamId);
      self:setIsChange(change, true);
end;

function fergusonsower:writeStream(streamId, connection)
      streamWriteBool(streamId, self.isChange);	
end;

function fergusonsower:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
		if self.synchronizeFillLevel then		
		
			local isChange = Utils.getNoNil(getXMLBool(xmlFile, key .. "#isChange"), false);
			if isChange ~= nil then
				self:setIsChange(isChange);
			end;

			self.fillLevel = Utils.getNoNil(getXMLFloat(xmlFile, key .."#fillLevel"));	
			self.fillType = Utils.getNoNil(getXMLString(xmlFile, key.."#fillType"));	
		end;
    return BaseMission.VEHICLE_LOAD_OK;
end;
  
function fergusonsower:getSaveAttributesAndNodes(nodeIdent)
	local attributes = ' ';

	local mystring = 'isChange ="' .. tostring(self.isChange) ..'"';	
	attributes = attributes .. mystring;
    local node = nil;
	return attributes, node;
end;

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

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

function fergusonsower:update(dt)
	   
	
		if self:getIsActiveForInput() then
			if InputBinding.isPressed(InputBinding.IMPLEMENT_EXTRA) and self.PTOId then
				self.printWarningTime = self.time + 1500;
			end;
            if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA) then
                self:setIsTurnedOn(not self.isTurnedOn);
            end;
			if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA2) then
				self:setIsChange(not self.isChange);
				self:setIsTurnedOn(false);

			end;			
		end;
      if self:getIsActive() then			
         if self.isTurnedOn and self.fillLevel > 0 then
			for k,spinner in pairs(self.spinners) do
				rotate(spinner.node, 0, (-0.016 * spinner.direction)*dt, 0);
			end;    
			if not self.fertiliserSoundEnabled and self:getIsActiveForSound() then
                playSample(self.fertiliserSound, 0, self.fertiliserSoundVolume, 0);
                setSamplePitch(self.fertiliserSound, self.fertiliserSoundPitchOffset);
                self.fertiliserSoundEnabled = true;
            end;
		end;
		if self.isChange then	
			self.aiTerrainDetailChannel1 = g_currentMission.ploughChannel;
			self.aiTerrainDetailChannel2 = g_currentMission.sowingChannel;
		end;
		if not self.isChange then
			self.aiTerrainDetailChannel1 = g_currentMission.cultivatorChannel;
			self.aiTerrainDetailChannel2 = g_currentMission.ploughChannel;
		end;
	end; 
	
end;

function fergusonsower:updateTick(dt)
    if self:getIsActive() then
		if self.PTOId then
			self:setIsTurnedOn(false)
		end;
		local isKeyEvent = false;	
		if self.isTurnedOn then
 			isKeyEvent = true;	
		else
 			isKeyEvent = false;	
		end;
		self:setVehicleRpmUp(dt, isKeyEvent);	
		if self.fillLevel <= 0 then
			self:setIsTurnedOn(false);
		end;
        if self.isClient then
			if not self.isTurnedOn and self.fertiliserSoundEnabled then
				stopSample(self.fertiliserSound);
                self.fertiliserSoundEnabled = false;
            end;
		end;
		if self.isTurnedOn and not self.PTOId and self.fillLevel >= 0 then
			if self.isChange then 
				Utils.setEmittingState(self.fertParticleSystems, true);
				Utils.setEmittingState(self.seedsParticleSystems, false);			
			elseif not self.isChange then
				Utils.setEmittingState(self.seedsParticleSystems, true);
				Utils.setEmittingState(self.fertParticleSystems, false);			
			end;
		else
			Utils.setEmittingState(self.fertParticleSystems, false);
			Utils.setEmittingState(self.seedsParticleSystems, false);
		end;
		
	end;

end;

function fergusonsower:draw()

	if self.isClient 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;	
		if self.printWarningTime > self.time then
			g_currentMission:addWarning(g_i18n:getText("turnON_Error"), 0.018, 0.033);
		end;
		if self.isChange then
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("seeder"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA2);
		else
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("sprayer"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA2);
		end;
		if self.isChange then
			--if self.fillLevel > 0 then
				self.FruitTypeOverlay:render();
			--end;
		end;		
	end;
end;

function fergusonsower:onDeactivate()
      self:setIsTurnedOn(false, true)
      fergusonsower.onDeactivateSounds(self);
end;
  
function fergusonsower:onDeactivateSounds()
      if self.fertiliserSoundEnabled then
          stopSample(self.fertiliserSound);
          self.fertiliserSoundEnabled = false;
      end;
end;
  
function fergusonsower:onAttach(attacherVehicle)
	self.attacherVehicle = attacherVehicle;
	if self.attacherVehicleCopy == nil then
		self.attacherVehicleCopy = self.attacherVehicle;
	end;
	self.saveMinRpm = self.attacherVehicle.motor.minRpm;
end; 	

function fergusonsower:onDetach()
	if self.fertParticleSystems ~= nil then
		Utils.setEmittingState(self.fertParticleSystems, false);
	end; 
	if self.seedsParticleSystems ~= nil then
		Utils.setEmittingState(self.seedsParticleSystems, false);
	end; 
	fergusonsower.onDeactivateSounds(self)	
	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 fergusonsower:onLeave()
	if self.deactivateOnLeave then
		fergusonsower.onDeactivate(self);
	else
		fergusonsower.onDeactivateSounds(self);
	end;
	if self.fertParticleSystems ~= nil then
		Utils.setEmittingState(self.fertParticleSystems, false);
	end;
	if self.seedsParticleSystems ~= nil then
		Utils.setEmittingState(self.seedsParticleSystems, false);
	end; 	
end;

function fergusonsower:onDeactivate()
    self:setIsTurnedOn(false, true);
	fergusonsower.onDeactivateSounds(self)
 	if self.fertParticleSystems ~= nil then
		Utils.setEmittingState(self.fertParticleSystems, false);
	end;
	if self.seedsParticleSystems ~= nil then
		Utils.setEmittingState(self.seedsParticleSystems, false);
	end; 	
end;

function fergusonsower:setIsChange(change, noEventSend)
	SetChangeEvent.sendEvent(self, change, noEventSend)
	self.isChange = change;
	if self.fillTypes ~= nil then
		if self.isChange then
			self.fillTypes[Fillable.FILLTYPE_FERTILIZER] = true;
			self.fillTypes[Fillable.FILLTYPE_SEEDS] = false;
		else
			self.fillTypes[Fillable.FILLTYPE_SEEDS] = true;
			self.fillTypes[Fillable.FILLTYPE_FERTILIZER] = false;
		end;
	end;
		if self.fillLevel > 0 then
			if self.currentFillType ~= fillType then
				self.fillLevel = 0;
				self.currentFillType = Fillable.FILLTYPE_UNKNOWN;
			end;
			if self.isClient then
				if self.currentFillPlane ~= nil then
					for _, node in ipairs(self.currentFillPlane.nodes) do
						setVisibility(node.node, false);
					end;
					self.currentFillPlane = nil;
				end;
			end;
		end;
end;

function fergusonsower:setIsTurnedOn(turnedOn, noEventSend)
      SetTurnedOnEvent.sendEvent(self, turnedOn, noEventSend)
      self.isTurnedOn = turnedOn;
end;

function fergusonsower: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;


SetChangeEvent = {};
SetChangeEvent_mt = Class(SetChangeEvent, Event);
  
InitEventClass(SetChangeEvent, "SetChangeEvent");
  
function SetChangeEvent:emptyNew()
     local self = Event:new(SetChangeEvent_mt);
      self.className="SetChangeEvent";
      return self;
end;
  
function SetChangeEvent:new(vehicle, change)
      local self = SetChangeEvent:emptyNew()
      self.vehicle = vehicle;
      self.change = change;
      return self;
end;
  
function SetChangeEvent:readStream(streamId, connection)
      local id = streamReadInt32(streamId);
      self.change = streamReadBool(streamId);
      self.vehicle = networkGetObject(id);
      self:run(connection);
end;
  
function SetChangeEvent:writeStream(streamId, connection)
      streamWriteInt32(streamId, networkGetObjectId(self.vehicle));
      streamWriteBool(streamId, self.change);
end;
  
function SetChangeEvent:run(connection)
	  if self.vehicle ~= nil then
		self.vehicle:setIsChange(self.change, true);
	  end;
      if not connection:getIsServer() then
         g_server:broadcastEvent(self, false, connection, self.vehicle);
      end;
end;
  
function SetChangeEvent.sendEvent(vehicle, change, noEventSend)
      if change ~= vehicle.isChange then
          if noEventSend == nil or noEventSend == false then
              if g_server ~= nil then
                  g_server:broadcastEvent(SetChangeEvent:new(vehicle, change), nil, nil, vehicle);
              else
                  g_client:getServerConnection():sendEvent(SetChangeEvent:new(vehicle, change));
              end;
          end;
      end;
end;
