local zone
local maxSpeed = 0
local maxRotationSpeed = 0
local bEnabled = true
local bActive = false
function OnScriptLoaded(level, obj)
  game.SubObject.Sleep(obj)
  zone = obj.Parent.Parent
  game.SubObject.SetEntityZoneHandler(obj, zone)
  local attributes = obj:GetLuaTableAttributes({
    "maxSpeed",
    "maxRotationSpeed"
  })
  maxSpeed = attributes.maxSpeed
  maxRotationSpeed = attributes.maxRotationSpeed
end
function OnMarkerEnterZone(level, scriptObj, volumeGameObject, markerGameObject, markerId)
  if tostring(markerId) ~= tostring(3) then
    return
  end
  local boat = game.Boat.GetPlayerBoat()
  if boat == nil then
    return
  end
  SetActive(boat)
end
function OnMarkerExitZone(level, scriptObj, volumeGameObject, markerGameObject, markerId)
  if tostring(markerId) ~= tostring(3) then
    return
  end
  local boat = game.Boat.GetPlayerBoat()
  if boat == nil then
    return
  end
  SetInactive(boat)
end
function OnFirstStart(level, obj)
  bEnabled = obj:GetLuaTableAttribute("bEnabledOnStart")
end
function OnStart(level, obj)
  if bEnabled then
    zone:Show()
    local boat = game.Boat.GetPlayerBoat()
    if boat and boat:InsideZone(zone) then
      SetActive(boat)
    end
  else
    zone:Hide()
  end
end
function OnSaveCheckpoint(level, obj)
  return {bEnabled = bEnabled}
end
function OnRestoreCheckpoint(level, obj, savedInfo)
  bEnabled = savedInfo.bEnabled
end
function Enable()
  bEnabled = true
  OnStart()
end
function Disable()
  bEnabled = false
  OnStart()
  if bActive then
    SetInactive()
  end
end
function SetActive(boat)
  game.Boat.SetOverrideSpeedControlData(boat, {
    TargetMaxSpeed = maxSpeed,
    TargetMaxRotationSpeed = maxRotationSpeed,
    TargetAcceleration = 25,
    TargetAngularAcceleration = 230,
    MaxSpeedChangeRate = 1,
    MaxRotationSpeedChangeRate = 100,
    AccelerationChangeRate = 1,
    AngularAccelerationChangeRate = 1
  })
  bActive = true
end
function SetInactive(boat)
  if boat then
    game.Boat.ClearOverrideSpeedControlData(boat)
  else
    boat = game.Boat.GetPlayerBoat()
    if boat then
      game.Boat.ClearOverrideSpeedControlData(boat)
    end
  end
  bActive = false
end
function IsEnabled()
  return bEnabled
end
function IsActive()
  return bActive
end
