-- This Source Code Form is subject to the terms of the bCDDL, v. 1.1.
-- If a copy of the bCDDL was not distributed with this
-- file, You can obtain one at http://beamng.com/bCDDL-1.1.txt

local M = {}

local message = false
local oldHSDAV = 0
local oldHSUAV = 0
local oldLSDAV = 0
local oldLSUAV = 0

local function onInit()
    oldHSDAV = v.data.engine.highShiftDownAV
    oldHSUAV = v.data.engine.highShiftUpAV
    oldLSDAV = v.data.engine.lowShiftDownAV
    oldLSUAV = v.data.engine.lowShiftUpAV
end

local function updateGFX(dt)
    if v.data.engine.shiftableAuto == true then
        --allow manual shifting of automatic
        --disallow full manual
        --automatic mode
        if drivetrain.shifterMode == 0 then
            drivetrain.shifterMode = 3
            drivetrain.autoClutch = true
            drivetrain.manualShift = false
            if message == false then
                gui.message("Real automatic", 5, "shiftermode")
                message = true
            end
        else
            message = false
        end
        --disallow manual 1st and 2nd gear
        if drivetrain.shifterMode == 3 then
            if drivetrain.shifterPosition > 1 then 
                drivetrain.shifterPosition = 1
            end
        end        
        --prevent upshifting while braking
        if input.brake > 0.7 then
            v.data.engine.lowShiftDownAV = oldHSDAV
            v.data.engine.lowShiftUpAV = oldHSUAV
        else
            v.data.engine.lowShiftDownAV = oldLSDAV
            v.data.engine.lowShiftUpAV = oldLSUAV
        end
		--don't allow car to be above redline
		if drivetrain.gear > 0 and drivetrain.rpm > (v.data.engine.maxRPM + 1500) then
			drivetrain.gear = drivetrain.gear + 1
			drivetrain.shifterPosition = drivetrain.shifterPosition + 1
		end
    end
end

-- public interface
M.onInit      = onInit
M.updateGFX = updateGFX

return M