-- 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 engine

local function onReset()
   	engine = powertrain.getDevice("mainEngine") or powertrain.getDevicesByType("combustionEngine")[1]
	electrics.values['riderpresent']=0
	electrics.values['rollthrust'] = 0
	active = 1
	roll=0
	pitch=0
end

local roll=0
local spd=0
local str=0
local abs=math.abs
local min=math.min
local max=math.max
local clamp = clamp
local sin = math.sin
local angvr=0
local pitch=0
local active = 1
local lean = 0
local lmtr = 0

local function updateGFX(dt)
	roll,pitch = obj:getRollPitchYaw()
	angvr = obj:getRollPitchYawAngularVelocity()
	spd = electrics.values.airspeed

	str=str-( clamp((str-(input.steering))*100,-1.5,1.5) *dt)

	lean=lean-( clamp((lean-(clamp(str,-0.1,0.1)*15))*100,-1.5,-1.5) *dt)

	if active == 1 then
		if electrics.values.gear == -1 then
			electrics.values['rollthrust'] = (roll*1) + (angvr*-0.005)
		else
			electrics.values['rollthrust'] = (0*min(spd*0.1,1)*1.5) + (roll*4) + (angvr*-0.02)
		end
		electrics.values['bikesteer'] = str

		--if spd > 50 then
			--if lmtr == 0 then
				--lmtr=1
				--engine:setTempRevLimiter(engine.outputAV1)
			--end
		--elseif spd < 29 then
		--	if lmtr == 1 then
		--		lmtr=0
		--		engine:resetTempRevLimiter()
		--	end
		--end
	end
	if abs(roll)>0.9 or abs(pitch)>0.6 then
    		--beamstate.breakBreakGroup("riderfall")
		controller.mainController.setEngineIgnition(false)
		electrics.values['riderpresent']=1
		electrics.values['rollthrust'] = 0
		active=0
	elseif spd < 1 and abs(roll)<0.05 then
		active = 1
		electrics.values['riderpresent']=0
	end
	

end

-- public interface
M.init    = onReset
M.reset = onReset
M.updateGFX = updateGFX

return M
