--***********************************************************
--**                  Written by Beathoven                 **
--***********************************************************

local BRAKE_STOP_SPEED_KMH = 0.5
local AIRBRAKE_COOLDOWN_MS = 1000
local brakedByVehicleId = {}
local lastAirbrakeAtByVehicleId = {}

Events.OnPlayerUpdate.Add(function(player)
   local vehicle = player.getVehicle and player:getVehicle() or nil
   if not vehicle then
      return
   end

   local scriptName = vehicle:getScriptName()
   if not scriptName or not string.find(scriptName, "Base%.SemiTruck") then
      return
   end

   local vehicleId = vehicle:getId()
   if not vehicle:isEngineRunning() then
      brakedByVehicleId[vehicleId] = true
      return
   end

   local speedKmh = math.abs(vehicle:getCurrentSpeedKmHour())
   local now = getTimestampMs and getTimestampMs() or 0
   local braked = brakedByVehicleId[vehicleId]
   if braked == nil then
      braked = true
   end

   if speedKmh <= BRAKE_STOP_SPEED_KMH and not braked then
      brakedByVehicleId[vehicleId] = true
      local lastAirbrakeAt = lastAirbrakeAtByVehicleId[vehicleId] or 0
      if now - lastAirbrakeAt >= AIRBRAKE_COOLDOWN_MS then
         lastAirbrakeAtByVehicleId[vehicleId] = now
         getSoundManager():PlayWorldSound("VehicleAirBrake", player:getCurrentSquare(), 1.0, 10.0, 1.0, true)
      end
      return
   end

   if speedKmh > BRAKE_STOP_SPEED_KMH and braked then
      brakedByVehicleId[vehicleId] = false
   end
end )