--[[
  @package    eg4-crank-ui-2
  @file       scroll-animation.lua
  @brief      Supports the scrolling animation for multi-page screens.
]]


local FPS = 20
local AUTO_DESTROY = 1
local DURATION = 200 -- ms

---
--- @brief  Animate the variable value
--- @param  variable  The variable animate
--- @param  value Target value
local id
local last_value = 0
function animate_variable(variable, value)
  if id then
    if last_value == value then
      return
    end
    last_value = value
    gre.animation_destroy(id)
  end

  local current_yoffset = gre.get_value(variable)
  if current_yoffset == value then return end

  id = gre.animation_create(FPS, AUTO_DESTROY, function()
    id = nil
    last_value = nil
  end)

  gre.animation_add_step(id, {
    rate = "easeinout",
    duration = DURATION,
    from = current_yoffset,
    to = value,
    key = variable,
  })
  gre.animation_trigger(id, {
    context = variable:object_parent(),
    id=variable,
  })
end

---
--- @brief  Animate the scrolling operations of menus and lists
--- @param  object  The variable animate
--- @param  yoffset Target value
function animate_scroll(object, yoffset)
  animate_variable(object..".grd_yoffset", yoffset)
end
