  --
  -- SowingMachineNew
  -- Class for all sowing machines
  --
  -- @author  Stefan Geiger
  -- @date  25/02/08
  --
  -- Copyright (C) GIANTS Software GmbH, Confidential, All Rights Reserved.
  
  source("dataS/scripts/vehicles/specializations/SetTurnedOnEvent.lua");
  source("dataS/scripts/vehicles/specializations/SowingMachineAreaEvent.lua");
  source("dataS/scripts/vehicles/specializations/SowingMachineSetIsFillingEvent.lua");
  source("dataS/scripts/vehicles/specializations/SowingMachineSetSeedIndex.lua");
  
  SowingMachineNew = {};
  
  function SowingMachineNew.prerequisitesPresent(specializations)
      return SpecializationUtil.hasSpecialization(Fillable, specializations) and SpecializationUtil.hasSpecialization(fergusonsower, specializations);
  end;
  
  function SowingMachineNew:load(xmlFile)
  
      -- self.setIsTurnedOn = SpecializationUtil.callSpecializationsFunction("setIsTurnedOn");
      self.setSeedFruitType = SpecializationUtil.callSpecializationsFunction("setSeedFruitType");
      self.setSeedIndex = SpecializationUtil.callSpecializationsFunction("setSeedIndex");
  
      --self.getAllowFillFromAir = Utils.overwrittenFunction(self.getAllowFillFromAir, SowingMachineNew.getAllowFillFromAir);
      self.getDirectionSnapAngle = Utils.overwrittenFunction(self.getDirectionSnapAngle, SowingMachineNew.getDirectionSnapAngle);
      --self.allowFillType = Utils.overwrittenFunction(self.allowFillType, SowingMachineNew.allowFillType);
      --self.setFillLevel = Utils.overwrittenFunction(self.setFillLevel, SowingMachineNew.setFillLevel);
      --self.getFillLevel = Utils.overwrittenFunction(self.getFillLevel, SowingMachineNew.getFillLevel);
      self.resetFillLevelIfNeeded = Utils.overwrittenFunction(self.resetFillLevelIfNeeded, SowingMachineNew.resetFillLevelIfNeeded);
  
      -- assert(self.setIsSowingMachineFilling == nil, "SowingMachineNew needs to be the first specialization which implements setIsSowingMachineFilling");
      self.setIsSowingMachineFilling = SowingMachineNew.setIsSowingMachineFilling;
      self.addSowingMachineFillTrigger = SowingMachineNew.addSowingMachineFillTrigger;
      self.removeSowingMachineFillTrigger = SowingMachineNew.removeSowingMachineFillTrigger;
  
      self.fillLitersPerSecond = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.fillLitersPerSecond"), 500);
      self.isSowingMachineFilling = false;
  
      self.sowingMachineFillTriggers = {};
      self.sowingMachineFillActivatable = SowingMachineFillActivatable:new(self);
  
      self.allowFillFromAirWhileTurnedOn = Utils.getNoNil(getXMLBool(xmlFile, "vehicle.allowFillFromAirWhileTurnedOn#value"), true);
  
      self.sowingDirectionNode = Utils.getNoNil(Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.sowingDirectionNode#index")), self.components[1].node);
  
      self.useDirectPlanting = Utils.getNoNil(getXMLBool(xmlFile, "vehicle.useDirectPlanting"), false);
  
      self.maxSpeedLevel = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.maxSpeedLevel#value"), 1);
      self.speedViolationMaxTime = 2500;
      self.speedViolationTimer = self.speedViolationMaxTime;
  
      self.seeds = {};
      local seedFruitTypes = getXMLString(xmlFile, "vehicle.seedFruitTypes#seedFruitTypes");
      if seedFruitTypes ~= nil and seedFruitTypes ~= "" then
          local types = Utils.splitString(" ", seedFruitTypes);
          for _,v in pairs(types) do
              local fruitTypeDesc = FruitUtil.fruitTypes[v];
              if fruitTypeDesc ~= nil and fruitTypeDesc.allowsSeeding then
                  table.insert(self.seeds, fruitTypeDesc.index);
              else
                  print("Warning: '"..self.configFileName.. "' has invalid seedFruitType '"..v.."'.");
              end;
          end;
      else
          local useSeedingWidth = Utils.getNoNil(getXMLBool(xmlFile, "vehicle.seedFruitTypes#useSeedingWidth"), false);
          for k, fruitTypeDesc in pairs(FruitUtil.fruitTypes) do
              if fruitTypeDesc.allowsSeeding and useSeedingWidth == fruitTypeDesc.useSeedingWidth then
                  table.insert(self.seeds, fruitTypeDesc.index);
              end;
          end;
      end;
      --self.seeds = { FruitUtil.FRUITTYPE_WHEAT, FruitUtil.FRUITTYPE_BARLEY, FruitUtil.FRUITTYPE_RAPE, FruitUtil.FRUITTYPE_MAIZE, FruitUtil.FRUITTYPE_GRASS};
  
      self.isTurnedOn = false;
      self.needsActivation = Utils.getNoNil(getXMLBool(xmlFile, "vehicle.needsActivation#value"), false);
  
      self.aiTerrainDetailChannel1 = g_currentMission.cultivatorChannel;
      self.aiTerrainDetailChannel2 = g_currentMission.ploughChannel;
      if self.useDirectPlanting then
          self.aiTerrainDetailChannel3 = g_currentMission.sowingChannel;
      end
	  
      self.groundParticleSystems = {};
      local entry = {};
      entry.ps = {};
      Utils.loadParticleSystem(xmlFile, entry.ps, "vehicle.groundParticleSystem", self.components, false, nil, self.baseDirectory);
      if table.getn(entry.ps) > 0 then
          entry.isActive = false;
          table.insert(self.groundParticleSystems, entry);
      end
      local i=0;
      while true do
          local baseName = string.format("vehicle.groundParticleSystems.groundParticleSystem(%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.groundParticleSystems, entry);
          end
          i = i+1;
      end; 
      if self.isClient then
          -- load sowing sound
          self.sowingSoundEnabled = false;
          local sowingSound = getXMLString(xmlFile, "vehicle.sowingSound#file");
          if sowingSound ~= nil and sowingSound ~= "" then
              sowingSound = Utils.getFilename(sowingSound, self.baseDirectory);
              self.sowingSound = createSample("sowingSound");
              loadSample(self.sowingSound, sowingSound, false);
              self.sowingSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.sowingSound#pitchOffset"), 0);
              self.sowingSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.sowingSound#volume"), 1.0);
              setSamplePitch(self.sowingSound, self.sowingSoundPitchOffset);
          end;
   
          local changeSeedInputButtonStr = getXMLString(xmlFile, "vehicle.changeSeedInputButton");
          if changeSeedInputButtonStr ~= nil then
              self.changeSeedInputButton = InputBinding[changeSeedInputButtonStr];
          end;
          self.changeSeedInputButton = Utils.getNoNil(self.changeSeedInputButton, InputBinding.IMPLEMENT_EXTRA3);
      end;
  
      self.fillTypes[Fillable.FILLTYPE_SEEDS] = true;
  
      self.lastSowingArea = 0;
  
      self.currentSeed = 1;
      self.allowsSeedChanging = true;
      self.showFieldNotOwnedWarning = false;
	  self.seedingBed = false;

end;
  
function SowingMachineNew:delete()
      for _, v in pairs(self.groundParticleSystems) do
          Utils.deleteParticleSystem(v.ps);
      end;
      if self.sowingSound ~= nil then
          delete(self.sowingSound);
          self.sowingSound = nil;
      end;
end;
  
function SowingMachineNew:readStream(streamId, connection)
      local seedIndex = streamReadUInt8(streamId);
      local turnedOn = streamReadBool(streamId);
      local isSowingMachineFilling = streamReadBool(streamId);
      self:setSeedIndex(seedIndex, true);
      self:setIsTurnedOn(turnedOn, true);
      self:setIsSowingMachineFilling(isSowingMachineFilling, true);
end;
  
function SowingMachineNew:writeStream(streamId, connection)
      streamWriteUInt8(streamId, self.currentSeed);
      streamWriteBool(streamId, self.isTurnedOn);
      streamWriteBool(streamId, self.isSowingMachineFilling);
end;
  
  
function SowingMachineNew:readUpdateStream(streamId, timestamp, connection)
      if connection:getIsServer() then
          self.showFieldNotOwnedWarning = streamReadBool(streamId);
      end;
end;
  
function SowingMachineNew:writeUpdateStream(streamId, connection, dirtyMask)
      if not connection:getIsServer() then
          streamWriteBool(streamId, self.showFieldNotOwnedWarning);
      end;
end;
  
function SowingMachineNew:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
      local selectedSeedFruitType = getXMLString(xmlFile, key.."#selectedSeedFruitType");
      if selectedSeedFruitType ~= nil then
          local fruitTypeDesc = FruitUtil.fruitTypes[selectedSeedFruitType];
          if fruitTypeDesc ~= nil then
              self:setSeedFruitType(fruitTypeDesc.index, true);
          end;
      end;
      return BaseMission.VEHICLE_LOAD_OK;
end;
  
function SowingMachineNew:getSaveAttributesAndNodes(nodeIdent)
      local selectedSeedFruitTypeName = "unknown";
      local selectedSeedFruitType = self.seeds[self.currentSeed];
      if selectedSeedFruitType ~= nil and selectedSeedFruitType ~= FruitUtil.FRUITTYPE_UNKNOWN then
          selectedSeedFruitTypeName = FruitUtil.fruitIndexToDesc[selectedSeedFruitType].name;
      end;
      local attributes = 'selectedSeedFruitType="'..selectedSeedFruitTypeName..'"';
      return attributes, nil;
end;
  
  
function SowingMachineNew:mouseEvent(posX, posY, isDown, isUp, button)
end;
  
function SowingMachineNew:keyEvent(unicode, sym, modifier, isDown)
end;
  
function SowingMachineNew:update(dt)

      if self:getIsActive() then
		if not self.isChange then 	  
          if self:getIsActiveForInput() then
              if InputBinding.hasEvent(self.changeSeedInputButton) then
  
                  if self.allowsSeedChanging then
                      local seed = self.currentSeed + 1;
                      if seed > table.getn(self.seeds) then
                          seed = 1;
                      end;
                      self:setSeedIndex(seed);
                  end;
              end;
          end;
      end
  end;
end;
  
function SowingMachineNew:updateTick(dt)
	if not self.isChange then
      if self:getIsActive() then
          local showFieldNotOwnedWarning = false;
  
          self.lastSowingArea = 0;
   
          local foldAnimTime = self.foldAnimTime;
          if self.isTurnedOn then
              if self.isServer then
                  local hasSeeds = (self.fillLevel > 0);
                  local useFillLevel = true;
                  if self.capacity == 0 or self:getIsHired() then
                      useFillLevel = false;
                      hasSeeds = true;
                  end;
                  if hasSeeds then
                      local cuttingAreasSend = {};
                      for k, cuttingArea in pairs(self.cuttingAreas) do
                          if self:getIsAreaActive(cuttingArea) then
                              local x,_,z = getWorldTranslation(cuttingArea.start);
                              if g_currentMission:getIsFieldOwnedAtWorldPos(x,z) then
                                  local x1,_,z1 = getWorldTranslation(cuttingArea.width);
                                  local x2,_,z2 = getWorldTranslation(cuttingArea.height);
                                  table.insert(cuttingAreasSend, {x,z,x1,z1,x2,z2});
                              else
                                  showFieldNotOwnedWarning = true;
                              end
                          end
                      end
  
                      if (table.getn(cuttingAreasSend) > 0) then
                          local seedsFruitType = self.seeds[self.currentSeed];
                          local dx,dy,dz = localDirectionToWorld(self.sowingDirectionNode, 0, 0, 1);
  
                          local angleRad = Utils.getYRotationFromDirection(dx, dz)
                          local desc = FruitUtil.fruitIndexToDesc[seedsFruitType];
                          if desc ~= nil and desc.directionSnapAngle ~= 0 then
                              angleRad = math.floor(angleRad / desc.directionSnapAngle + 0.5) * desc.directionSnapAngle;
                          end
  
                          local angle = Utils.convertToDensityMapAngle(angleRad, g_currentMission.terrainDetailAngleMaxValue);
  
                          local area, detailArea = SowingMachineAreaEvent.runLocally(cuttingAreasSend, seedsFruitType, angle, self.useDirectPlanting)
                          if area > 0 or detailArea > 0 then
                              if area > 0 then
                                  local fruitDesc = FruitUtil.fruitIndexToDesc[seedsFruitType];
  
                                  local pixelToSqm = g_currentMission:getFruitPixelsToSqm();
                                  local sqm = area*pixelToSqm;
                                  local ha = sqm/10000;
  
                                  self.lastSowingArea = sqm;
  
                                  local usage = fruitDesc.seedUsagePerSqm*sqm;
                                  g_currentMission.missionStats.seedUsageTotal = g_currentMission.missionStats.seedUsageTotal + usage;
                                  g_currentMission.missionStats.seedUsageSession = g_currentMission.missionStats.seedUsageSession + usage;
  
                                  g_currentMission.missionStats.hectaresSeededTotal = g_currentMission.missionStats.hectaresSeededTotal + ha;
                                  g_currentMission.missionStats.hectaresSeededSession = g_currentMission.missionStats.hectaresSeededSession + ha;
  
								  self.seedingBed = true;									
                                  if useFillLevel then
                                      self:setFillLevel(self.fillLevel - usage, self.currentFillType);
                                  else
                                      local fillTypeDesc = Fillable.fillTypeIndexToDesc[Fillable.FILLTYPE_SEEDS]
                                      if fillTypeDesc ~= nil then
                                          local price = usage*fillTypeDesc.pricePerLiter;
                                          g_currentMission.missionStats.expensesTotal = g_currentMission.missionStats.expensesTotal + price;
                                          g_currentMission.missionStats.expensesSession = g_currentMission.missionStats.expensesSession + price;
  
                                          g_currentMission:addSharedMoney(-price, "other");
                                      end
                                  end
                              end
                              g_server:broadcastEvent(SowingMachineAreaEvent:new(cuttingAreasSend, seedsFruitType, angle, self.useDirectPlanting));
							else
								local usage = 1*dt*0.001;
								local usageHired = 0;
								if useFillLevel and not self.seedingBed then
                                      self:setFillLevel(self.fillLevel - usage, self.currentFillType);
								elseif not useFillLevel then
									self:setFillLevel(self.fillLevel - usageHired, self.currentFillType);
								end;							  
                          end;
						else
                          if self.fillLevel > 0 then
							  local usage = self.defaultSprayLitersPerSecond * dt*0.001;
                              self:setFillLevel(self.fillLevel - usage, self.currentFillType);
                          end;
                      end;
                  end;
              end;
              g_currentMission.missionStats.seedingDurationTotal = g_currentMission.missionStats.seedingDurationTotal + dt/(1000*60);
              g_currentMission.missionStats.seedingDurationSession = g_currentMission.missionStats.seedingDurationSession + dt/(1000*60);
          end
  
          if self.isClient then
               for _,ps in pairs(self.groundParticleSystems) do
                  local enabled = (self.isTurnedOn and self.lastSpeed*3600 > 5)
                  if enabled and ps.cuttingArea ~= nil and self.cuttingAreas[ps.cuttingArea] ~= nil then
                      enabled = self:getIsAreaActive(self.cuttingAreas[ps.cuttingArea]);
                  end
                  if ps.isActive ~= enabled then
                      ps.isActive = enabled;
                      Utils.setEmittingState(ps.ps, ps.isActive);
                  end
              end
              if self.sowingSound ~= nil then
                  if self.isTurnedOn then
                      if not self.sowingSoundEnabled  and self:getIsActiveForSound() then
                          playSample(self.sowingSound, 0, self.sowingSoundVolume, 0);
                          self.sowingSoundEnabled = true;
                      end
                  else
                      if self.sowingSoundEnabled then
                          self.sowingSoundEnabled = false;
                          stopSample(self.sowingSound);
                      end
                  end
              end
          end
  
          local speedLimit = 20;
          if self.maxSpeedLevel == 2 then
              speedLimit = 30;
          elseif self.maxSpeedLevel == 3 then
              speedLimit = 100;
          end;
          if self.isTurnedOn and self:doCheckSpeedLimit() and self.lastSpeed*3600 > speedLimit then
              self.speedViolationTimer = self.speedViolationTimer - dt;
          else
              self.speedViolationTimer = self.speedViolationMaxTime;
          end
          if self.isServer then
              if showFieldNotOwnedWarning ~= self.showFieldNotOwnedWarning then
                  self.showFieldNotOwnedWarning = showFieldNotOwnedWarning;
              end
          end
      end;
  
      if self.isServer and self.isSowingMachineFilling then
          local delta = 0;
          if self.sowingMachineFillTrigger ~= nil then
              delta = self.fillLitersPerSecond*dt*0.001;
              delta = self.sowingMachineFillTrigger:fillSowingMachine(self, delta);
          end
  
          if delta <= 0 then
              self:setIsSowingMachineFilling(false);
          end;
      end
	end;
end;
  
function SowingMachineNew:draw()
   	if not self.isChange then 
      if self.isClient then
          if self:getIsActiveForInput(true) then
              if self.fillLevel <= 0 and self.capacity ~= 0 then
                  g_currentMission:addExtraPrintText(g_i18n:getText("FirstFillTheTool"));
              end;
  
              if self.allowsSeedChanging and table.getn(self.seeds) > 1 then
                  g_currentMission:addHelpButtonText(g_i18n:getText("ChooseSeed"), self.changeSeedInputButton);
              end;
  
              -- if self.needsActivation then
                  -- if self.isTurnedOn then
                      -- g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_off_OBJECT"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA);
                  -- else
                      -- if (self.fillLevel > 0 or self.capacity == 0) then
                          -- g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_on_OBJECT"), self.typeDesc), InputBinding.IMPLEMENT_EXTRA);
                      -- end;
                  -- end;
              -- end;
          end
  
          g_currentMission:setFruitOverlayFruitType(self.seeds[self.currentSeed]);
  
          if math.abs(self.speedViolationTimer - self.speedViolationMaxTime) > 2 then
              local buttonName = InputBinding.SPEED_LEVEL1;
              if self.maxSpeedLevel == 2 then
                  buttonName = InputBinding.SPEED_LEVEL2;
              elseif self.maxSpeedLevel == 3 then
                  buttonName = InputBinding.SPEED_LEVEL3;
              end;
              g_currentMission:addWarning(g_i18n:getText("Dont_drive_to_fast") .. "\n" .. string.format(g_i18n:getText("Cruise_control_levelN"), tostring(self.maxSpeedLevel)), 0.07+0.022, 0.019+0.029);
          elseif self.showFieldNotOwnedWarning then
              g_currentMission:addWarning(g_i18n:getText("You_dont_own_this_field"));
          end;
      end;
	end;
end;
  
function SowingMachineNew:onAttach(attacherVehicle)
      SowingMachineNew.onActivate(self);
end;
  
function SowingMachineNew:onDetach()
      if self.deactivateOnDetach then
          SowingMachineNew.onDeactivate(self);
      else
          SowingMachineNew.onDeactivateSounds(self);
      end;
end;
  
function SowingMachineNew:onEnter(isControlling)
      if isControlling then
          SowingMachineNew.onActivate(self);
      end;
end;
  
function SowingMachineNew:onLeave()
      if self.deactivateOnLeave then
          SowingMachineNew.onDeactivate(self);
      end;
end;
  
function SowingMachineNew:onActivate()
end;
  
function SowingMachineNew:onDeactivate()
      for _, ps in pairs(self.groundParticleSystems) do
          if ps.isActive then
              ps.isActive = false;
              Utils.setEmittingState(ps.ps, false);
          end;
      end;
      self.speedViolationTimer = self.speedViolationMaxTime;
      self.showFieldNotOwnedWarning = false;
      self:setIsTurnedOn(false, true);
      SowingMachineNew.onDeactivateSounds(self);
end;
  
-- function SowingMachineNew:setIsTurnedOn(turnedOn, noEventSend)
      -- SetTurnedOnEvent.sendEvent(self, turnedOn, noEventSend)
      -- self.isTurnedOn = turnedOn;
-- end;
  
function SowingMachineNew:onDeactivateSounds()
      if self.sowingSoundEnabled then
          self.sowingSoundEnabled = false;
          stopSample(self.sowingSound);
      end;
end;
  
function SowingMachineNew:setSeedIndex(seedIndex, noEventSend)
      SowingMachineSetSeedIndex.sendEvent(self, seedIndex, noEventSend);
      self.currentSeed = math.min(math.max(seedIndex, 1), table.getn(self.seeds));
  
      if self.useDirectPlanting then
          self.aiProhibitedFruitType = self.seeds[self.currentSeed];
          -- do not allow any of the fruit we are seeding
          self.aiProhibitedMinGrowthState = 0;
          self.aiProhibitedMaxGrowthState = FruitUtil.fruitIndexToDesc[self.aiProhibitedFruitType].maxHarvestingGrowthState;
      else
          self.aiProhibitedFruitType = FruitUtil.FRUITTYPE_UNKNOWN;
      end
end;
  
function SowingMachineNew:setSeedFruitType(fruitType, noEventSend)
      for i,v in ipairs(self.seeds) do
          if v == fruitType then
              self:setSeedIndex(i, noEventSend);
              break;
          end;
      end;
end;
  
function SowingMachineNew:aiTurnOn()
  
      self:setIsTurnedOn(true, true);
  
end;
  
function SowingMachineNew:aiLower()
      self:setIsTurnedOn(true, true);
end;
  
function SowingMachineNew:aiRaise()
      self:setIsTurnedOn(false, true);
end;
  --[[
function SowingMachineNew:getAllowFillFromAir(superFunc)
      if self.isTurnedOn and not self.allowFillFromAirWhileTurnedOn and not self.isChange then
          return false;
      end
      return superFunc(self);
end]]
  
function SowingMachineNew:getDirectionSnapAngle(superFunc)
      local seedsFruitType = self.seeds[self.currentSeed];
      local desc = FruitUtil.fruitIndexToDesc[seedsFruitType];
      local snapAngle = 0;
      if desc ~= nil then
          snapAngle = desc.directionSnapAngle;
      end
      return math.max(snapAngle, superFunc(self));
end
  --[[
  -- overwrite Fillable.resetFillLevelIfNeeded
function SowingMachineNew:resetFillLevelIfNeeded(superFunc, fillType)
      -- we convert everything to seeds
	  if not self.isChange then
		superFunc(self, Fillable.FILLTYPE_SEEDS);
	else
		superFunc(self, Fillable.FILLTYPE_FERTILIZER);
	  end
end;
  
  -- overwrite Fillable.allowFillType
function SowingMachineNew:allowFillType(superFunc, fillType, allowEmptying)
      return self.fillTypes[fillType] == true;
end;
  
  -- overwrite Fillable.setFillLevel
function SowingMachineNew:setFillLevel(superFunc, fillLevel, fillType, force)
  
      -- convert everything to seeds if it is accepted
	if not self.isChange then
		if self:allowFillType(fillType, false) then
			fillType = Fillable.FILLTYPE_SEEDS;
		end
	else
		fillType = Fillable.FILLTYPE_FERTILIZER;
	end;
  
      superFunc(self, fillLevel, fillType, force);
end
  
  -- overwrite Fillable.getFillLevel
function SowingMachineNew:getFillLevel(superFunc, fillType)
      return self.fillLevel;
end
  ]]
function SowingMachineNew:setIsSowingMachineFilling(isFilling, noEventSend)
      SowingMachineSetIsFillingEvent.sendEvent(self, isFilling, noEventSend)
       if self.isSowingMachineFilling ~= isFilling then
          self.isSowingMachineFilling = isFilling;
  
          self.sowingMachineFillTrigger = nil;
          if isFilling then
              -- find the first trigger which is activable
              for i, trigger in ipairs(self.sowingMachineFillTriggers) do
                  if trigger:getIsActivatable(self) then
                      self.sowingMachineFillTrigger = trigger;
                      break;
                  end;
              end;
          end
      end;
end;
  
function SowingMachineNew:addSowingMachineFillTrigger(trigger)
      if table.getn(self.sowingMachineFillTriggers) == 0 then
          g_currentMission:addActivatableObject(self.sowingMachineFillActivatable);
      end;
      table.insert(self.sowingMachineFillTriggers, trigger);
end;
  
function SowingMachineNew:removeSowingMachineFillTrigger(trigger)
      for i=1, table.getn(self.sowingMachineFillTriggers) do
          if self.sowingMachineFillTriggers[i] == trigger then
              table.remove(self.sowingMachineFillTriggers, i);
              break;
          end;
      end;
      if table.getn(self.sowingMachineFillTriggers) == 0 then
          if self.isServer then
              self:setIsSowingMachineFilling(false);
          end;
          g_currentMission:removeActivatableObject(self.sowingMachineFillActivatable);
      end;
end;
  
SowingMachineFillActivatable = {}
local SowingMachineFillActivatable_mt = Class(SowingMachineFillActivatable);
  
function SowingMachineFillActivatable:new(SowingMachineNew)
      local self = {};
      setmetatable(self, SowingMachineFillActivatable_mt);
  
      self.SowingMachineNew = SowingMachineNew;
      self.activateText = "unknown";
  
      return self;
end;
  
  
function SowingMachineFillActivatable:getIsActivatable()
      if self.SowingMachineNew:getIsActiveForInput() and self.SowingMachineNew.fillLevel < self.SowingMachineNew.capacity and not self.SowingMachineNew.isChange  then
          -- find the first trigger which is activable
          for i,trigger in ipairs(self.SowingMachineNew.sowingMachineFillTriggers) do
              if trigger:getIsActivatable(self.SowingMachineNew) then
                  self:updateActivateText();
				  -- if self.SowingMachineNew.fillLevel <= 0 then
						-- fergusonsower:setIsChange(false);
				  -- end;				  
                  return true;
              end;
          end;
      end
      return false;
end;
  
function SowingMachineFillActivatable:onActivateObject()
      self.SowingMachineNew:setIsSowingMachineFilling(not self.SowingMachineNew.isSowingMachineFilling);
      self:updateActivateText();
      g_currentMission:addActivatableObject(self);
end;
  
function SowingMachineFillActivatable:drawActivate()
      -- TODO draw icon
end;
  
function SowingMachineFillActivatable:updateActivateText()
      if self.SowingMachineNew.isSowingMachineFilling and not self.SowingMachineNew.isChange then
          self.activateText = string.format(g_i18n:getText("stop_refill_OBJECT"), self.SowingMachineNew.typeDesc);
      else
          self.activateText = string.format(g_i18n:getText("refill_OBJECT"), self.SowingMachineNew.typeDesc);
      end;
end;