  --
  -- ForageWagons
  -- Class for all ForageWagons
  --
  -- @author  Stefan Geiger
  -- @date  25/06/08
  --
  -- Copyright (C) GIANTS Software GmbH, Confidential, All Rights Reserved.
  
  ForageWagons = {};
  
  source("dataS/scripts/vehicles/specializations/SetTurnedOnEvent.lua");
  source("dataS/scripts/vehicles/specializations/ForageWagonAreaEvent.lua");
  
  function ForageWagons.prerequisitesPresent(specializations)
      return SpecializationUtil.hasSpecialization(Trailer, specializations);
  end;
  
  function ForageWagons:load(xmlFile)
  
      self.setIsTurnedOn = SpecializationUtil.callSpecializationsFunction("setIsTurnedOn");
  
      self.forageWgnSoundEnabled = false;
      if self.isClient then
          local forageWgnSound = getXMLString(xmlFile, "vehicle.forageWgnSound#file");
          if forageWgnSound ~= nil and forageWgnSound ~= "" then
              forageWgnSound = Utils.getFilename(forageWgnSound, self.baseDirectory);
              self.forageWgnSound = createSample("forageWgnSound");
              loadSample(self.forageWgnSound, forageWgnSound, false);
              self.forageWgnSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.forageWgnSound#pitchOffset"), 1);
              self.forageWgnSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.forageWgnSound#volume"), 1.0);
              setSamplePitch(self.forageWgnSound, self.forageWgnSoundPitchOffset);
          end;
      end
  
      -- Backward compatibility: Convert non-windrow fill types to the correspoding windrow fill types
      if Utils.getNoNil(getXMLBool(xmlFile, "vehicle.fillTypes#convertToWindrowFillType"), true) then
          local fillTypesToAdd = {};
          for fillType, enabled in pairs(self.fillTypes) do
              if fillType ~= Fillable.FILLTYPE_UNKNOWN and enabled then
                  local fruitType = FruitUtil.fillTypeToFruitType[fillType];
                  if fruitType ~= nil and not FruitUtil.fillTypeIsWindrow[fillType] then
                      local windrowFillType = FruitUtil.fruitTypeToWindrowFillType[fruitType];
                      if windrowFillType ~= nil and not self.fillTypes[windrowFillType] then
                          self.fillTypes[fillType] = nil;
                          table.insert(fillTypesToAdd, windrowFillType);
                          print("Warning: converted non-windrow fill type to windrow fill type in "..self.configFileName);
                      end
                  end
              end
          end
          for _,fillType in pairs(fillTypesToAdd) do
              self.fillTypes[fillType] = true;
          end
      end
  
      self.pickupAnimationName = Utils.getNoNil(getXMLString(xmlFile, "vehicle.pickupAnimation#name"), "");
      if self.playAnimation == nil or self.getIsAnimationPlaying == nil then
          self.pickupAnimationName = "";
      end;
      self.pickupAnimationLowerSpeed = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.pickupAnimation#lowerSpeed"), 1);
      self.pickupAnimationLiftSpeed = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.pickupAnimation#liftSpeed"), -self.pickupAnimationLowerSpeed);
  
      self.turnedOnRotationNodes = {};
      local i = 0;
      while true do
          local key = string.format("vehicle.turnedOnRotationNodes.turnedOnRotationNode(%d)", i);
          if not hasXMLProperty(xmlFile, key) then
              break;
          end;
          local node = Utils.indexToObject(self.components, getXMLString(xmlFile, key.."#index"));
          local rotSpeed = math.rad(Utils.getNoNil(getXMLFloat(xmlFile, key.."#rotSpeed"), 1)*0.001);
          if node ~= nil then
              table.insert(self.turnedOnRotationNodes, {node=node, rotSpeed=rotSpeed});
          end;
          i = i + 1;
      end;
  
      self.fillScale = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.fillScale#value"), 1);
      self.wasToFast = false;
      self.isTurnedOn = false;
  
      self.lastForageWagonArea = 0;
  
      self.forageWagonGroundFlag = self:getNextDirtyFlag();
  end;
  
  function ForageWagons:delete()
      if self.forageWgnSound ~= nil then
          delete(self.forageWgnSound);
      end;
  end;
  
  function ForageWagons:readStream(streamId, connection)
      local turnedOn = streamReadBool(streamId);
      self:setIsTurnedOn(turnedOn, true);
  end;
  
  function ForageWagons:writeStream(streamId, connection)
      streamWriteBool(streamId, self.isTurnedOn);
  end;
  
  function ForageWagons:readUpdateStream(streamId, timestamp, connection)
  end;
  
  function ForageWagons:writeUpdateStream(streamId, connection, dirtyMask)
  end;
  
  function ForageWagons:mouseEvent(posX, posY, isDown, isUp, button)
  end;
  
  function ForageWagons:keyEvent(unicode, sym, modifier, isDown)
  end;
  
  function ForageWagons:update(dt)

            if self.fillLevel == self.capacity then
                           g_currentMission:addWarning(g_i18n:getText("mh_OVERFLOW2"));
          end;
  
      if self:getIsActiveForInput() then
          if InputBinding.hasEvent(InputBinding.ZAKRYTIE) then
              self:setIsTurnedOn(not self.isTurnedOn);
          end;
      end;
 if self.isTurnedOn then
            if self.fillLevel == self.capacity then
        self.attacherVehicle.motor.maxRpm[1]=0;
        self.attacherVehicle.motor.maxRpm[2]=0;
        self.attacherVehicle.motor.maxRpm[3]=0;
else
        self.attacherVehicle.motor.maxRpm[1]=860;
        self.attacherVehicle.motor.maxRpm[2]=960;
        self.attacherVehicle.motor.maxRpm[3]=2000;
     end;
   end;
  end;
  
  function ForageWagons:updateTick(dt)
      self.wasToFast = false;
      self.lastForageWagonArea = 0;
      if self:getIsActive() then
          if self.isTurnedOn then
              if self.fillLevel < self.capacity then
  
                  local toFast = self:doCheckSpeedLimit() and self.lastSpeed*3600 > 29;
                  self.wasToFast = toFast;
                  if self.isServer then
                      if not toFast then
                          local cuttingAreasSend = {};
                          for k, cuttingArea in pairs(self.cuttingAreas) do
                              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;
                          if (table.getn(cuttingAreasSend) > 0) then
                              local fruitTypeFix = false;
                              local fruitType = FruitUtil.FRUITTYPE_UNKNOWN;
                              if self.fillLevel > self.capacity*self.fillTypeChangeThreshold and FruitUtil.fillTypeToFruitType[self.currentFillType] ~= nil and FruitUtil.fillTypeIsWindrow[self.currentFillType] then
                                  fruitTypeFix = true;
                                  fruitType = FruitUtil.fillTypeToFruitType[self.currentFillType];
                              end
                              local area, usedFruitType = ForageWagonAreaEvent.runLocally(cuttingAreasSend, self.fillTypes, fruitTypeFix, fruitType);
                              if area > 0 then
                                  self.lastForageWagonArea = area;
  
                                  local pixelToSqm = g_currentMission:getFruitPixelsToSqm(); -- 4096px are mapped to 2048m
                                  local literPerSqm = FruitUtil.getFillTypeLiterPerSqm(FruitUtil.fruitTypeToWindrowFillType[usedFruitType], 1);
                                  local sqm = area*pixelToSqm;
  
                                  local deltaLevel = sqm*literPerSqm * self.fillScale;
  
                                  self:setFillLevel(self.fillLevel+deltaLevel, FruitUtil.fruitTypeToWindrowFillType[usedFruitType], true);
                                  g_server:broadcastEvent(ForageWagonAreaEvent:new(cuttingAreasSend, usedFruitType));
                              end;
                          end;
                      end;
                  end;
              end
  
              if not self.forageWgnSoundEnabled and self.forageWgnSound ~= nil and self:getIsActiveForSound() then
                  playSample(self.forageWgnSound, 0, self.forageWgnSoundVolume, 0);
                  self.forageWgnSoundEnabled = true;
              end;
  
              if self.isTurnedOn then
                  for _, node in pairs(self.turnedOnRotationNodes) do
                      rotate(node.node, 0, -dt*node.rotSpeed, 0);
                      if self.setMovingToolDirty ~= nil then
                          self:setMovingToolDirty(node.node);
                      end
                  end
              end
          end;
  
      end;
  end;
  
  function ForageWagons:draw()
      if self.wasToFast then
          g_currentMission:addWarning(g_i18n:getText("Dont_drive_to_fast") .. "\n" .. string.format(g_i18n:getText("Cruise_control_levelN"), "2"), 0.07+0.022, 0.019+0.029);
      end;
      if self:getIsActiveForInput(true) then
          if self.isTurnedOn then
              g_currentMission:addHelpButtonText(string.format(g_i18n:getText("zakryt")), InputBinding.ZAKRYTIE);
          else
              g_currentMission:addHelpButtonText(string.format(g_i18n:getText("otkryt")), InputBinding.ZAKRYTIE);
          end;
      end;
		local prozent = self.fillLevel/self.capacity*100;
		if prozent > 0 then
	              local fillType = Fillable.fillTypeIndexToDesc[self.currentFillType];
		renderText(0.75, 0.72, 0.02,""..string.format("Straw: %.0f (%d%%)", self.fillLevel, prozent).."");
		end;

            if self.fillLevel == self.capacity then
	              setTextBold(true);
                            setTextColor(1.0, 0.0, 0.0, 1.0); 
		renderText(0.75, 0.70, 0.02, g_i18n:getText("mh_OVERFLOW"));
          end;
  end;
  
  function ForageWagons:onDetach()
      if self.deactivateOnDetach then
          ForageWagons.onDeactivate(self);
      else
          ForageWagons.onDeactivateSounds(self);
      end;
  end;
  
  function ForageWagons:onLeave()
      if self.deactivateOnLeave then
          ForageWagons.onDeactivate(self);
      else
          ForageWagons.onDeactivateSounds(self);
      end;
  end;
  
  function ForageWagons:onDeactivate()
      self:setIsTurnedOn(false, true)
      ForageWagons.onDeactivateSounds(self);
  end;
  
  function ForageWagons:setIsTurnedOn(isTurnedOn, noEventSend)
      SetTurnedOnEvent.sendEvent(self, isTurnedOn, noEventSend)
      self.isTurnedOn = isTurnedOn;
  
      if self.pickupAnimationName ~= "" then
          local animTime = nil;
          if self:getIsAnimationPlaying(self.pickupAnimationName) then
              animTime = self:getAnimationTime(self.pickupAnimationName);
          end;
          if isTurnedOn then
              self:playAnimation(self.pickupAnimationName, self.pickupAnimationLowerSpeed, animTime, true)
          else
              self:playAnimation(self.pickupAnimationName, self.pickupAnimationLiftSpeed, animTime, true)
          end;
      end;
  
      if not isTurnedOn then
          if self.forageWgnSoundEnabled then
              stopSample(self.forageWgnSound);
              self.forageWgnSoundEnabled = false;
          end;
      end
  end;
  
  function ForageWagons:onDeactivateSounds()
      if self.forageWgnSoundEnabled then
          stopSample(self.forageWgnSound);
          self.forageWgnSoundEnabled = false;
      end;
  end;