local p = {}

local state

local function stateName(args)
	local dualabbrs = {NT = "Northern Territory", WA = "Western Australia"}
	
	local data = mw.loadData("Module:Jct/statename/data")
	local abbr = args.state or args.province
	local country = args.country
	if country == 'AUS' then
		return dualabbrs[abbr] or data.statenames[abbr]
	else
		return data.statenames[abbr]
	end
end

local function location(args, num)
	local city = args["city" .. num]
	local location = args["location" .. num]
	local areadab = args["areadab" .. num]
	local countydab = args["countydab" .. num]
	
	if not(city or location) then
		return ''
	end
	
	local parts
	if num == 1 then
		parts = {" – "}
	else
		parts = {", "}
	end
	
	if location then
		table.insert(parts, location)
		return table.concat(parts)
	end
	
	table.insert(parts, "[[" .. city)
	if areadab then
		table.insert(parts, " (" .. areadab .. ")")
	end
	if countydab then
		table.insert(parts, ", " .. countydab .. " County")
	end
	if state then
		table.insert(parts, ", " .. state)
	end
	
	table.insert(parts, "|" .. city .. "]]")
	return table.concat(parts)
end

function p.city(frame)
	local pframe = frame:getParent()
	local config = frame.args -- the arguments passed BY the template, in the wikitext of the template itself
	local args = pframe.args -- the arguments passed TO the template, in the wikitext that transcludes the template
	
	local city1 = args.city1 or args.location1
	if not city1 then
		return ''
	end
	
	state = stateName(args)
	local cities = {}
	for i = 1, 4 do
		cities[i] = location(args, i)
	end
	return table.concat(cities)
end

return p