local p = {}

local codis = mw.loadData("Module:llengua/taula") -- taula llengua - script
local scripts = mw.loadData("Module:llengua/script") -- taula script - style
local synonyms = mw.loadData ('Module:llengua/ISO 639 synonyms') -- ISO 639-2/639-2T code translation to 639-1 code

local function isSet( var )
	return not (var == nil or var == '')
end

--[[extracts and returns IETF language tag parts:
	primary language subtag (required) - 2 or 3 character IANA language code
	script subtag - four character IANA script code
	region subtag - two-letter or three digit IANA region code
	variant subtag - four digit or 5-8 alnum variant code; only one variant subtag supported
	private subtag - x- followed by 1-8 alnum private code; only supported with the primary language tag

in any one of these forms
	lang					lang-variant
	lang-script				lang-script-variant
	lang-region				lang-region-variant
	lang-script-region		lang-script-region-variant
	lang-x-private	
	
each of lang, script, region, variant, and private, when used, must be valid

Languages with both two- and three-character code synonyms are promoted to the two-character synonym because
the IANA registry file omits the synonymous three-character code; we cannot depend on browsers understanding
the synonymous three-character codes in the lang= attribute.

returns six  values; all lower case.  Valid parts are returned as themselves; omitted parts are returned as empty strings, invalid
parts are returned as nil; the sixth returned item is an error message (if an error detected) or nil.

see http://www.rfc-editor.org/rfc/bcp/bcp47.txt section 2.1

]]

local function get_ietf_parts(source, args_script, args_region, args_variant)
	local code, script, region, variant, private								-- ietf tag parts

	if not isSet(source) then
		return nil, nil, nil, nil, nil, 'missing language tag'
	end

	local pattern = {															-- table of tables holding acceptibe ietf tag patterns and short names of the ietf part captured by the pattern
		{'^(%a%a%a?)%-(%a%a%a%a)%-(%a%a)%-(%d%d%d%d)$', 's', 'r', 'v'}, 				-- 1 -  ll-Ssss-RR-variant (where variant is 4 digits)
		{'^(%a%a%a?)%-(%a%a%a%a)%-(%d%d%d)%-(%d%d%d%d)$', 's', 'r', 'v'},				-- 2 -  ll-Ssss-DDD-variant (where region is 3 digits; variant is 4 digits)
		{'^(%a%a%a?)%-(%a%a%a%a)%-(%a%a)%-(%w%w%w%w%w%w?%w?%w?)$', 's', 'r', 'v'},		-- 3 -  ll-Ssss-RR-variant (where variant is 5-8 alnum characters)
		{'^(%a%a%a?)%-(%a%a%a%a)%-(%d%d%d)%-(%w%w%w%w%w%w?%w?%w?)$', 's', 'r', 'v'},	-- 4 -  ll-Ssss-DDD-variant (where region is 3 digits; variant is 5-8 alnum characters)
		
		{'^(%a%a%a?)%-(%a%a%a%a)%-(%d%d%d%d)$', 's', 'v'},						-- 5 -  ll-Ssss-variant (where variant is 4 digits)
		{'^(%a%a%a?)%-(%a%a%a%a)%-(%w%w%w%w%w%w?%w?%w?)$', 's', 'v'},			-- 6 -  ll-Ssss-variant (where variant is 5-8 alnum characters)
		
		{'^(%a%a%a?)%-(%a%a)%-(%d%d%d%d)$', 'r', 'v'},							-- 7 -  ll-RR-variant (where variant is 4 digits)
		{'^(%a%a%a?)%-(%d%d%d)%-(%d%d%d%d)$', 'r', 'v'},						-- 8 -  ll-DDD-variant (where region is 3 digits; variant is 4 digits)
		{'^(%a%a%a?)%-(%a%a)%-(%w%w%w%w%w%w?%w?%w?)$', 'r', 'v'},				-- 9 -  ll-RR-variant (where variant is 5-8 alnum characters)
		{'^(%a%a%a?)%-(%d%d%d)%-(%w%w%w%w%w%w?%w?%w?)$', 'r', 'v'},				-- 10 - ll-DDD-variant (where region is 3 digits; variant is 5-8 alnum characters)
		
		{'^(%a%a%a?)%-(%d%d%d%d)$', 'v'},										-- 11 - ll-variant (where variant is 4 digits)
		{'^(%a%a%a?)%-(%w%w%w%w%w%w?%w?%w?)$', 'v'},							-- 12 - ll-variant (where variant is 5-8 alnum characters)
		
		{'^(%a%a%a?)%-(%a%a%a%a)%-(%a%a)$', 's', 'r'},							-- 13 - ll-Ssss-RR
		{'^(%a%a%a?)%-(%a%a%a%a)%-(%d%d%d)$', 's', 'r'},						-- 14 - ll-Ssss-DDD (region is 3 digits)
		
		{'^(%a%a%a?)%-(%a%a%a%a)$', 's'},										-- 15 - ll-Ssss
		
		{'^(%a%a%a?)[%-_](%a%a)$', 'r'},											-- 16 - ll-RR
		{'^(%a%a%a?)%-(%d%d%d)$', 'r'},											-- 17 - ll-DDD (region is 3 digits)
		
		{'^(%a%a%a?)$'},														-- 18 - ll
		
		{'^(%a%a%a?)%-x%-(%w%w?%w?%w?%w?%w?%w?%w?)$', 'p'},						-- 19 - ll-x-pppppppp (private is 1-8 alnum characters)
		}

	local t = {}										-- table of captures; serves as a translator between captured ietf tag parts and named variables

	for i, v in ipairs(pattern) do						-- spin through the pattern table looking for a match
		local c1, c2, c3, c4							-- captures in the 'pattern' from the pattern table go here
	
		c1, c2, c3, c4 = source:match(pattern[i][1])	-- one or more captures set if source matches pattern[i])
		if c1 then										-- c1 always set on match
			code = c1									-- first capture is always code
			t = {
				[pattern[i][2] or 'x'] = c2,			-- fill the table of captures with the rest of the captures
				[pattern[i][3] or 'x'] = c3,			-- take index names from pattern table and assign sequential captures
				[pattern[i][4] or 'x'] = c4,			-- index name may be nil in pattern[i] table so "or 'x'" spoofs a name for this index in this table
				}
			script = t.s or ''							-- translate table contents to named variables;
			region = t.r or ''							-- absent table entries are nil so set named ietf parts to empty string for concatenation
			variant= t.v or ''
			private = t.p or ''
			break										-- and done
		end
	end
	
	if not code then
		return nil, nil, nil, nil, nil, table.concat ({'unrecognized language tag: ', source}) -- don't know what we got but it is malformed
	end
	
	code = code:lower()				-- ensure that we use and return lower case version of this
	if synonyms[code] then			-- if 639-2/639-2T code has a 639-1 synonym
		code = synonyms[code]		-- use the synonym
	end
	if codis[code] == nil and mw.language.fetchLanguageName(code, 'ca') == '' then
		return nil, nil, nil, nil, nil, table.concat({'unrecognized language code: ', code}) -- invalid language code, don't know about the others (don't care?)
	end
	
	if not isSet(script) then
		script = args_script or ''						-- use args.script if provided
	end 
	if isSet(script) then
		script = string.sub(script, 1, 1):upper() .. string.sub(script, 2):lower()
		if not scripts[script] then
			return code, nil, nil, nil, nil, table.concat({'unrecognized script: ', script, ' for code: ', code});	-- language code ok, invalid script, don't know about the others (don't care?)
		end
	end
	
	if not isSet(region) then
		region = args_region or ''						-- use args.region if provided
	end
	region = region:upper()
	
	if not isSet(variant) then
		variant = args_variant or ''					-- use args.variant if provided
	end 
	variant = variant:lower()						-- ensure that we use and return lower case version of this
	
	if isSet(private) then
		private = private:lower()						-- ensure that we use and return lower case version of this
	end
	
	return code, script, region, variant, private, nil	-- return the good bits; make sure that msg is nil
end

-- Plantilla:lang
function p.lang(frame)
	local args = frame:getParent().args
	local codi = isSet(args[1]) and args[1]
	local text = isSet(args[2]) and args[2]
	local sc = isSet(args.sc) and args.sc
	local tr = isSet(args.tr) and args.tr
	local style = isSet(args.style) and args.style
	local ret = text or ''
	
	if not (codi and text) then
		error("És necessari proporcionar dos paràmetres.")
	end
	
	if not sc and codis[codi] then
		sc = codis[codi].script
	end
	if not sc then
		_, sc = get_ietf_parts(codi)
	end
	
	local family
	if isSet(sc) and sc ~= "Latn" then
		if scripts[sc] then
			family = scripts[sc].family
			style = style or scripts[sc].style
		else
			error(sc .. ": no està definit")
		end
	end
	
	if codi ~= "ca" or family then
		ret = '<span'
		if codi ~= "ca" then
			ret = ret .. ' lang="' .. codi .. '"'
		end
		if family or style then
			ret = ret .. ' style="' .. (family or '') .. (style or '') .. '"'
		end
		ret = ret .. '>' .. text .. '</span>'
		if tr then
			ret = ret .. ', <span style="font-style: italic;">' .. tr .. '</span>'
		end
	end
	
    return ret
end

-- Cerca el nom de llengua definit a /taula o en la llibreria de MediaWiki
local function language_name_get(code)
	if not code then return end
	local name
	if codis[code] then
		name = codis[code].nom
	end
	if name == nil then
		name = mw.language.fetchLanguageName(code, 'ca') -- ca = nom en català
	end
	if not isSet(name) then
		return
	end
	return name
end

function p.nom(codi)
	if type(codi) == "table" then codi = codi.args[1] end -- des de plantilles via invoke o des de mòduls via require
	if codi == nil then
		return
	end
	local nom = language_name_get(codi)
	if not nom then
		nom = language_name_get(get_ietf_parts(codi))
	end
	if not nom and codi:match('^%a%a%a?%p') then
		require('Module:utilitats').rastreig("langname")
	end
    return nom or codi
end

return p