--[[
  @package    eg4-crank-ui-2
  @file       state-of-charge.lua
  @brief      Supports the state of charge features and notifications
]]

--[[
./iogen g4_frontend - state_of_charge 1s0:text "return { active = true, info_code = '00', charge_level='90%' }"
]]

local TILE = "state_of_charge"
local NOTIFICATION = "state_of_charge_no_data"
local info = {}

---
-- @brief  Updates the state of charge icon.
--
function show_state_of_charge()
  return sbsettings.check_can_protocol_active("STATE-OF-CHARGE")
end

---
--- @brief  Process state of charge info code template update
--- @param  gre#context mapargs
function cb_process_state_of_charge(mapargs)
  local data = loadstring(mapargs.context_event_data.text)()
  info.data = data

  local message = get_state_of_charge_driver_message(data.info_code)
  if data.active then
    if message ~= "" then
      if data.charge_level then
        local specifier = get_state_of_charge_driver_specifier()
        if specifier ~= "" then
          -- Uses gsub to fix up issue with single %
          message = message:gsub(specifier, (data.charge_level == "") and "??" or data.charge_level:gsub("%%", "%%%%"))
        end
      end
      gre.set_value("status_tiles_layer."..TILE..".message.text", message)
      activate_tile(TILE)
      close_notifications(NOTIFICATION)
    end
  else
    deactivate_tile(TILE)
  end
end

---
--- @brief  Toggle the state of charge display override
--- @param  gre#context mapargs
function cb_toggle_state_of_charge(mapargs)
  send_event("toggle_state_of_charge_display_override")
  local data = info.data or {}
  local message = get_state_of_charge_driver_message(data.info_code)
  if message == "" then
    local group = notify(NOTIFICATION)
    if data.charge_level then
      local format = gre.get_value(group..".status.format")
      message = string.format(format, (data.charge_level == "") and "??" or tostring(data.charge_level))
    end
    gre.set_value(group..".status.value", message)
  end
end

