-- 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 lfr1
local lfr2
local rfr1
local rfr2

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

	for _, node in pairs(v.data.nodes) do
		if node.name == "fr5l" then
			lfr1=node.cid	
		elseif node.name == "fr6" then
			lfr2=node.cid	
		elseif node.name == "fr5r" then
			rfr1=node.cid	
		elseif node.name == "fr6" then
			rfr2=node.cid	
		end
	end
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

		 --  		1.5	1.0		0.2						0.2		0.2
--				kP, 	kI, 		kD, 	minOutput, 	maxOutput,  	integralInCoef,   integralOutCoef, 	minIntegral, maxIntegral
local rollPID = newPIDParallel(1, 	1,		0.08, 	-1,		1, 			0.2, 		0.2, 			-0.3, 0.3)


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

	str=str-( clamp((str-(input.steering))*1.5,-5/spd,5/spd) *dt)
	--str=str-( clamp((str-(input.steering))*1.5,-2,2) *dt)
	--str=input.steering


	if active == 1 then
		if electrics.values.gear == -1 then
			electrics.values['rollthrust'] = (roll*1) + (angvr*-0.005)
		else
			electrics.values['rollthrust'] = rollPID:get(-roll,clamp(clamp(str*5,-1,1)*clamp(spd*0.05,0.1,2),-1.5,1.5),dt)
		end

		electrics.values['bikesteer'] = input.steering
		electrics.values['lean'] = roll*-2 		--(-1+clamp(abs(angvr)*5,0,1))

	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.initSecondStage = onReset
M.updateData = onReset
M.updateGFX = updateGFX


return M
