Documentation[créer] [purger]
-- based on Module:Jumelages under CC BY-SA 3.0 et GFDL licenses

local linguistic = require 'Module:Linguistique'
local wd = require 'Module:Wikidata'

local gdata = mw.loadData('Module:Country data/liste')

local p = {}

local function getFlag(entity, atdate, label)
	local span = mw.html.create('span')
		:attr('data-sort-value', label)
	local flagOrCOA = wd.getClaims({entity = entity,
		property = {'P41', 'P94'}, numval=1, atdate = atdate})  -- drapeau ou blason
	if flagOrCOA then
		local mediaName = wd.formatStatement(flagOrCOA[1])
		if mediaName then
			span = span:node('[[Fichier:' .. mediaName .. '|border|20x15px|class=noviewer]]')
		end
	end
	return tostring(span:done())
end

local function getCity(statement)
	local entity = wd.getMainId(statement)
	local label = mw.wikibase.label(entity)
	local name = wd.formatStatement(statement, {showsource = true})
	local flag = getFlag(entity, 'today', label)
	return {flag, name or ''}
end

local function getCountryShortName(qid)
	-- On utilise Country data, qui permet d'obtenir "Chine" au lieu de
	-- "République de Chine" par exemple
	local countryKey = gdata[string.lower(qid)]
	if countryKey then
		local countryTable = require('Module:Country data/' .. countryKey)
		local name = countryTable and countryTable.name
		if name then
			if type(name) == 'string' then
				return name
			end
			if name.default then
				return name.default
			end
		end
	end
	return mw.wikibase.label(qid)
end

local function getCountry(statement)
	local entity = wd.getMainId(statement)
	local country = wd.getClaims({entity = entity, property = 'P17',
		numval=1, atdate = 'today'})
	if country then
		local countryEntity = wd.getMainId(country[1])
		local name = getCountryShortName(countryEntity)
		local nameWithLink = wd.formatEntity(countryEntity,
			{labelformat = function () return name end})
		local flag = getFlag(countryEntity, 'today', name)
		return {flag, nameWithLink}
	end
end

local function getCoordinates(entity)
	local coord = wd.getClaims({entity = entity, property = 'P625',
		numval=1})
	if not coord then
		return
	end
	
	local snak = coord[1].mainsnak
	if snak.snaktype ~= 'value' then
		return
	end
	local value = snak.datavalue.value
	value.repr = value.latitude .. ', ' .. value.longitude
	return value
end

local function getDefaultTitle(entity)
	local title = 'Affluents'
	local locationName = wd.getLabel(entity)
	if locationName then
		return title .. ' ' .. linguistic.of(locationName) .. '.'
	end
	return title .. '.'
end

local function compareClaimLabels(c1, c2)
	local label1 = mw.ustring.upper(mw.wikibase.label(wd.getMainId(c1)))
	local label2 = mw.ustring.upper(mw.wikibase.label(wd.getMainId(c2)))
	return label1 < label2
end

function p.tableauDesAffluents(frame)
	local args = frame:getParent().args
	
	-- Entité Wikidata
	local entity = wd.getEntity(args.wikidata)
	if not entity then
		error('Pas d\'entité Wikidata pour l\'élément.')
	end
	
	local watersources = wd.getClaims({entity = entity,
		property = 'P974', rank = 'valid'})
	
	if not watersources then
		return
	end
	-- Tri par nom d'affluent
	table.sort(watersources, compareClaimLabels)
	
	local title = args.titre
		or getDefaultTitle(entity)
		
	-- Bouton d'édition Wikidata
	title = wd.addLinkBack(title, entity, 'P974')

	local tab = mw.html.create('table')
		:addClass('wikitable')
		:addClass('centre')
		:addClass('sortable')
		:node('<caption>' .. title .. '</caption>') --titre
	
	local columns = {
		{fn = getCity, colName = 'Cours d\'eau', withFlag = 1},
		{fn = getCountry, colName = 'Pays', withFlag = 1}
	}
	
	local data = {}
	for _, statement in ipairs(watersources) do
		local watersourceData = {}
		for _, column in ipairs(columns) do
			local _, value = pcall(column.fn, statement)
			table.insert(watersourceData, value
				or (column.withFlag and {'', ''})
				or '')
			if value and not column.hasValues then
				column.hasValues = true
			end
		end
		table.insert(data, watersourceData)
	end

	local tr = mw.html.create('tr')
	for _, column in pairs(columns) do
		if column.hasValues then
			local th = mw.html.create('th')
				:attr('scope', 'col')
				:wikitext(column.colName)
			if column.withFlag then
				th = th:attr('colspan', 2)
			end
			tr = tr:node(th:done())
		end
	end
	tab = tab:node(tr:done())
	
	for _, watersourceData in ipairs(data) do
		local tr = mw.html.create('tr')
		for j, column in pairs(columns) do
			if column.hasValues then
				local value = watersourceData[j]
				if column.withFlag then
					tr = tr:node(mw.html.create('td')
						:css('border-right', 0)
						:wikitext(value[1] or ''):done())
					tr = tr:node(mw.html.create('td')
						:css('border-left', 0)
						:wikitext(value[2] or ''):done())
				else
					tr = tr:node(mw.html.create('td')
						:wikitext(value or ''):done())
				end
			end
		end
		tab = tab:node(tr:done())
	end
	
	tab = tostring(tab:done())
	
	return tab
end

return p