---
-- @package   eg4-crank-ui
-- @file      sbc-roller.lua
-- @brief     Functionality related to handling roller control.
--
-- @copyright Copyright 2020 Hanover Displays Limited.
-- @license   This program is the confidential and proprietary product of
--            Hanover Displays Limited. Any unauthorised use, reproduction or
--            transfer of this program is strictly prohibited. (Subject to
--            limited distribution and restricted disclosure only.) All
--            rights reserved.
--
--

local roller_active = {}
local roller_count = 0
local roller_timer = nil

---
-- @brief  Initialise roller with a value set
--
function InitialiseRoller(data, control, format, start_value, end_value)
  local rows = end_value - start_value + 3
  gre.set_table_attrs(control, { rows = rows })
  data[control..".text.1.1"] = ""
  data[control..".text."..rows..".1"] = ""
  for index = start_value,end_value do
    data[string.format(control..".text.%d.1", index - start_value + 2)] = string.format(format, index)
  end
end

---
-- @brief  Get active row for the roller.
--
function GetRow(control)
  local value = math.floor((120 - gre.get_value(control..".grd_yoffset")) / 81)
  if value < 1 then return 1 end
  local rows = gre.get_value(control..".grd_rows")
  if value > rows - 2 then return rows - 2 end
  return value
end

---
-- @brief  Set active row in the roller.
--
function SetRow(data, control, value)
  data[control..".grd_yoffset"] = ((1 - value) * 81)
end

---
-- @brief  Update the roller to click on each value change.
--
local function CBUpdateRoller()
  for control,value in pairs(roller_active) do
    local current = GetRow(control)
    if value ~= current then
      roller_active[control] = current
      CBClickOnScreenPress()
    end
  end
end

---
-- @brief  Start the roller in motion.
--
--- @param gre#context mapargs
function CBRollerScrollStart(mapargs) 
  if roller_active[mapargs.context_control] == nil then
    roller_active[mapargs.context_control] = GetRow(mapargs.context_control)
    roller_count = roller_count + 1
    if roller_count == 1 then
      roller_timer = gre.timer_set_interval(CBUpdateRoller,50)
    end
  end
end

---
-- @brief  Roller in motion stopped
--
--- @param gre#context mapargs
function CBRollerScrollComplete(mapargs)
  if roller_active[mapargs.context_control] ~= nil then
    roller_active[mapargs.context_control] = nil
    roller_count = roller_count - 1
    if roller_count == 0 then
      gre.timer_clear_interval(roller_timer)
      roller_timer = nil
    end
  end
end


