--[[
  @package eg4-crank-ui-2
  @file    mqtt-subscribe.lua
  @brief   Handles the MQTT subscribe events.
]]

local json = require "utils/json"

local GPS_TILE_GROUP = "system_information_layer.gps_info"

---
-- @brief  Subscribe to the MQTT topic
-- @param  mapargs.topic The topic to subscribe
-- @param  mapargs.event The event to trigger
function cb_mqtt_subscribe(mapargs)
  sbmodule.subscribe(mapargs.topic, mapargs.event)
end

---
-- @brief  Unsubscribe to the MQTT topic
-- @param  mapargs.topic The topic to unsubscribe
function cb_mqtt_unsubscribe(mapargs)
  sbmodule.unsubscribe(mapargs.topic)
end

---
--- @brief  Process the update on GNSS location run state
--- @param  mapargs.context_event_data.text  The GNSS location run state in JSON format
function cb_update_gnss_location_runstate(mapargs)
  local info = json.decode(mapargs.context_event_data.text)
  gre.set_value(GPS_TILE_GROUP..".grd_hidden", info.runState == "RUNNING" and 0 or 1)
end

--- @brief  Process the update on GNSS location
--- @param  mapargs.context_event_data.text  The GNSS location information in JSON format
function cb_update_gnss_location(mapargs)
  local populate = function(item, value)
    local control = GPS_TILE_GROUP.."."..item
    local format = gre.get_value(control..".format") or "%s"
    gre.set_value(control..".text", string.format(format, tostring(value or "")))
  end

  local info = json.decode(mapargs.context_event_data.text)
  populate("position", info and string.format("%0.5f, %0.5f", info.latitude, info.longitude) or "---")
  populate("satellites", info and info.numberOfSatellites)
  populate("hdop", info and info.hdop)
  populate("fix", info and info.fix)
end
