-- This is the script run to process uploaded config files
local functions, mac, data, device_id = ...

--APP.logevent("got to process_put script")

-- Get the params
local params = functions.get_device_params(device_id)

function process_polycom()
	local before, xml, after = string.match(data, "(.*<OVERRIDES)([^/]*)(/>.*)")
	if not xml then return end
	local attrs = {}
	for str in string.gmatch(xml, "%S+") do
		local n,v = string.match(str, "([^=]+)=\"(.*)\"")
		if not attrs[n] then
			attrs[n] = v
		end
	end

--	for n,v in pairs(attrs) do
--		APP.logevent("name "..n.." val "..(v or ""))
--	end

	-- Read attributes from attrs and generate paramaters for ACF
	local xmlout = {}
	for n,v in pairs(attrs) do 
		-- search attribute name for reg_name like "reg.1."
		--  and for rest like "fwdStatus"
		local num, rest = string.match(n, "reg%.(%d+)%.([%.%a]*)$")

		-- if rest is defined, then num is defined also
		if rest == "fwd.busy.contact" then
			params.value["reg"..num].value.forwardbusy.value = v
		elseif rest == "fwd.noanswer.contact" then
			params.value["reg"..num].value.forwardnoanswer.value = v
		elseif rest == "fwdContact" then
			params.value["reg"..num].value.forwardall.value = v
		elseif rest == "fwd.busy.status" then
			params.value["reg"..num].value.forwardbusyenable.value = (v == "1")
		elseif rest == "fwd.noanswer.status" then
			params.value["reg"..num].value.forwardnoanswerenable.value = (v == "1")
		elseif rest == "fwdStatus" then
			params.value["reg"..num].value.forwardallenable.value = (v == "1")
		elseif rest == "ringType" then
			params.value["reg"..num].value.polycomringtone.value = string.match(v, "%d+")
		else
			xmlout[#xmlout+1] = n.."=\""..v.."\""
		end
	end

	data = before.." "..table.concat(xmlout, " ").." "..after
end

-- Determine the template
if string.match(params.value.device.label, "Polycom") then
	process_polycom()
end

-- Update the params
local params = functions.set_device_params(params)

-- Return the updated data
return data
