Dokumentasjon for denne modulen kan opprettes på Modula:Wikidata/Flags/veahkki

local p = {};

function p.getFlag( parseTimeFromSnak, countryEntityOrId, actualDate )
	local flagClaims;
	if type( countryEntityOrId ) == "string" then
		flagClaims = mw.wikibase.getAllStatements( countryEntityOrId, 'P41' )
	elseif countryEntityOrId and countryEntityOrId.claims and countryEntityOrId.claims.P41 then
		flagClaims = countryEntityOrId.claims.P41
	end

	if not flagClaims or #flagClaims == 0 then
		return nil;
	end

	local countryFlags = {};
	for _, flagImageStatement in pairs( flagClaims ) do
		if flagImageStatement.rank ~= 'deprecated' then
			local flagImage;
			if flagImageStatement and
				flagImageStatement.mainsnak and
				flagImageStatement.mainsnak.datavalue and
				flagImageStatement.mainsnak.datavalue.value	and
    			not (flagImageStatement.qualifiers and flagImageStatement.qualifiers.P366)
			then
				flagImage = flagImageStatement.mainsnak.datavalue.value;
			end
			local flagStartTime = -9223372036854775808;
			if flagImageStatement.qualifiers and
				flagImageStatement.qualifiers.P580 and
				flagImageStatement.qualifiers.P580[ 1 ]
			then
				if type( parseTimeFromSnak ) == 'table' then
					parseTimeFromSnak = parseTimeFromSnak.parseTimeFromSnak;
				end
				local parsedFlagStartTime = parseTimeFromSnak( flagImageStatement.qualifiers.P580[ 1 ] );
				if parsedFlagStartTime then
					flagStartTime = parsedFlagStartTime;
				end
			end
			if flagImage then
				countryFlags[ flagStartTime ] = flagImage;
			end
		end
	end

	local goodFlag = nil;
	if countryFlags then
		local ordered_dates = {};
		for flagBeginDate in pairs( countryFlags ) do
			table.insert( ordered_dates, flagBeginDate );
		end
		table.sort( ordered_dates );

		for i = 1, #ordered_dates do
			local flagBeginDate, flag = ordered_dates[ i ], countryFlags[ ordered_dates[ i ] ];
			if actualDate >= flagBeginDate then
				goodFlag = flag;
			end
		end
	end
	if goodFlag then
		return '[[File:' .. goodFlag .. '|20x15px|border]]';
	end
	return nil;
end

return p;