require("luamods/command")
require("config/rsm_conf")
require("luamods/rsm_serials")



local flddEditor = {}

local pretty = require("pl.pretty")
local formatter = require("formatter")
local configPars = require("configParser")
local flddPath = "/etc/rsm/fldd/devices/"

function flddEditor:getXmlFiles()

  local templatesFiles = command.getFilesInTable(flddPath)
  local retTable = {}
  count=1

  for key, fileName in ipairs(templatesFiles) do
    xmlForFile =  configPars.parse(flddPath..fileName,"xml")
    retTable[count] = xmlForFile
    count=count+1
  end
  return retTable

end



function flddEditor:writeXmlFiles(filesTable)

command.ex([[rm ]]..flddPath.."*.xml")
  --print("In write xmlFiles")

  if filesTable[1] ~= nil then
    for key, fileInfo in ipairs(filesTable) do
      local  newSerial = rsm_serials.generateNewSerial()
      local newFile = newSerial..".xml"
      fileInfo["device"]["serial"].__value__ = newSerial
      --print(pretty.write(fileInfo))
      configPars.write(flddPath..newFile,"xml",fileInfo)
      formatter:replaceSingleQuotes(flddPath..newFile)
    end
  else
    local  newSerial = rsm_serials.generateNewSerial()
    local newFile = newSerial..".xml"
    filesTable["device"]["serial"].__value__ = newSerial
    configPars.write(flddPath..newFile,"xml",filesTable)
    formatter:replaceSingleQuotes(flddPath..newFile)
    --print(pretty.write(filesTable))
  end


end

return flddEditor
