-- 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 = {}
--Mandatory controller parameters
M.type = "auxiliary"
M.relevantDevice = "transfercase"

local max = math.max
local transfercase = nil
local initialSplitA = nil
local initialSplitB = nil
local initialViscousCoef = nil

local function updateGFX(dt)
  local escConfig = controller.getController("esc").getCurrentConfigData()
  if escConfig.name == "Drift ESC" then
    transfercase.diffTorqueSplitA = electrics.values.throttle
    transfercase.diffTorqueSplitB = 1 - transfercase.diffTorqueSplitA
    --transfercase.viscousCoef = 5
  else
    transfercase.diffTorqueSplitA = initialSplitA
    transfercase.diffTorqueSplitB = initialSplitB
    --transfercase.viscousCoef = initialViscousCoef
  end
end

local function init(jbeamData)
  local hasESC = controller.getController("esc") ~= nil
  if not hasESC then
    M.updateGFX = nop
  else
    transfercase = powertrain.getDevice("transfercase")
    if transfercase then
      initialSplitA = transfercase.diffTorqueSplitA
      initialSplitB = transfercase.diffTorqueSplitB
      initialViscousCoef = transfercase.viscousCoef
    else
      M.updateGFX = nop
    end
  end
end

M.init = init
M.updateGFX = updateGFX

return M