local m = {}

local helper = require("helper")

local filePath = "/var/tmp/usc/AppPrgData.json"

function m.CollectData(uscConfig)
  Logger:Info("-- usc_module.lua: collecting data")

  -- also deletes old file
  local file = io.open(filePath, "w")
  if file == nil then
    -- directory does probably not exist, create and try again
    local dirPath = filePath:match("(/.*)/.*")
    assert(os.execute("mkdir -p " .. dirPath))
    file = io.open(filePath, "w")
    if file == nil then
      Logger:Error("Failed to create file: " .. filePath)
      return
    end
  end

  file:write('{"appLoaded":true,')

  -- datalogger
  local dataLoggerAppConfig = uscConfig["datalogger"]
  file:write('"datalogger":{"enabled":', tostring(dataLoggerAppConfig.EnabledBool), '}')

  file:write(',')

  -- monitoring
  local monitoringAppConfig = uscConfig["monitoring"]
  file:write('"notifications":{"enabled":', tostring(monitoringAppConfig.EnabledBool),
    ',"count":', tostring(monitoringAppConfig.NumberOfNotifications), '}')

  file:write(',')

  -- recording
  local recordingAppConfig = uscConfig["recording"]
  file:write('"recordings":{"enabled":', tostring(recordingAppConfig.EnabledBool),
    ',"count":', tostring(recordingAppConfig.NumberOfRecordings), '}')

  file:write(',')

  -- app prg version
  local major, minor = helper.GetAppPrg1Version()
  file:write(string.format('"appPrgVersion":"%d.%d"', major, minor))

  file:write('}')
  file:close()

  Logger:Info("-- usc_module.lua: collected and saved data to " .. filePath)
end

function m.DeleteDataFile()
  Logger:Info("-- usc_module.lua: deleting " .. filePath)
  os.remove(filePath)
end

function m.TriggerSendingData()
  Logger:Info("-- usc_module.lua: notify client to send data")
  os.execute("killall -q -USR1 usage-statistics-client")
end

return m
