Documentation for this module may be created at Module:VN/doc

local p = {}

function p.main( frame )
	local hidelangs = {
		simple    = true,
		["en-gb"] = true,
		["en-ca"] = true
	}
	
	local frame = frame:getParent()
	local args = frame.args
	local result = ""
	--local wd = mw.wikibase.getEntity( 'Q140' )
	local wd = mw.wikibase.getEntity()
	local langnames = mw.language.fetchLanguageNames()
	local t = {}
	
	-- Add names added as arguments
	for key, val in pairs( args ) do 
		t[ key ] = { s = 'l', val = { val } }
	end
	
	-- Add names from Wikidata
	if wd and wd.claims and wd.claims.P1843 then
		for u, claim in pairs( wd.claims.P1843 ) do
			local vn = claim.mainsnak.datavalue.value
			local lang = vn.language
			vn = vn.text:gsub( "^%l", string.upper )
			if not hidelangs[ lang ] then
				if t[ lang ] and t[ lang ].s == 'd' then
					table.insert( t[ lang ].val, vn )
				else
					-- Two possibilities: 
					-- Option 1: Only available on Wikidata, or 
					-- Option 2: There are VNs on both Wikispecies and Wikidata.
					-- (These might not be the same. Would be difficult to 
					-- notice conflicts automatically, though.)
					-- Just use Wikidata, ignore local.
					t[ lang ] = { s = 'd', val = { vn } }
				end
			end
		end
	end
	
	-- Build the table
	result = [[<div style=
"padding:0 10px;
-moz-column-count: 2; 
-moz-column-gap: 40px;
-moz-column-rule: 1px solid #aaa;
-webkit-column-count: 2; 
-webkit-column-gap: 40px;
-webkit-column-rule: 1px solid #aaa;
column-count: 2; 
column-gap: 40px;
column-rule: 1px solid #aaa;
border:1px solid #aaa;
background:#f9f9f9;
color:#202122;
font-size:90%">
]]
	
	local q = {}
	
	for lang, name in pairs( t ) do
		local note = ""
		if name.s == 'l' then
			note = '<span style="color: black;" '..
				'title="The vernacular name listed here is only available locally, ' ..
				'and should be added to Wikidata.">*</span>'
		end
		
		--result = result .. note .. "'''" .. langnames[ lang ] .. ":''' " .. name.val .. "<br/>\n"
		if langnames[ lang ] then
			table.insert( q, { 
				lang = lang, 
				-- Actual content:
				note .. "'''" .. langnames[ lang ] .. ":'''&nbsp;" .. table.concat( name.val, ', ' ) .. "<br/>\n"
			} )
		end
	end
	
	-- Sort, by language code.
	table.sort( q, function( a, b ) return a.lang < b.lang end )
	
	for lang, content in pairs( q ) do
		result = result .. content[ 1 ]
	end
	
	
	result = result .. '</div>'
	
	return result
end

return p