--[[
  @package    eg4-crank-ui-2
  @file       repeater-control.lua
  @brief      Supports the action of a control that performs a repeated action while pressed.
]]

local info = {}

---
--- @brief  Update the control for the repeat action
--- @param  args  The control arguments
local function update(args)
  info.count = info.count + 1
  if info.count == 1 then
    gre.timer_clear_interval(info.timer_id)
    info.timer_id = gre.timer_set_interval(update, 100)
  elseif info.count == 6 and info.args.accelerate == 1 then
    gre.timer_clear_interval(info.timer_id)
    info.timer_id = gre.timer_set_interval(update, 50)
  elseif info.count == 16 and info.args.accelerate == 1 then
    gre.timer_clear_interval(info.timer_id)
    info.timer_id = gre.timer_set_interval(update, 25)
  end

  cb_activity_monitoring_restart()

  if _G[info.args.fn](info.args) then
    gre.timer_clear_interval(info.timer_id)
    info.timer_id = nil
  end
end

---
--- @brief  Callback to handle repeat actions for a control
function cb_repeat_action(mapargs)
  if mapargs.context_event == "gre.press" then
    info = {}
    info.args = mapargs
    info.count = 0
    info.timer_id = gre.timer_set_interval(update, 500)
    return
  end

  if mapargs.context_event == "gre.touch" then
    if info.count == 0 then
      _G[mapargs.fn](mapargs)
    end
  end

  if info.timer_id then
    gre.timer_clear_interval(info.timer_id)
    info.timer_id = nil
  end
end
