Documentation for this module may be created at Մոդուլ:Wikidata/Countries/doc

local moduleDates = require( "Module:Dates" );

local p = {}

local function calculateEndDateTimestamp( context, options, statement )
	if (not context) then error('context not specified') end;
	if (not options) then error('options not specified') end;
	if (not options.entity) then error('options.entity missing') end;
	if (not statement) then error('statement not specified') end;

	if ( statement.qualifiers and statement.qualifiers.P582 ) then
		for i, qualifier in ipairs(statement.qualifiers.P582 ) do
			local parsedTime = context.parseTimeFromSnak( qualifier );
			if ( parsedTime ) then
				return parsedTime;
			end
		end
	end

	-- check death day... do we have it at all?
	for h, propertyId in pairs( { "P570", "P577", "P571" } ) do
		local dateClaims = context.selectClaims( options, propertyId );
		if ( dateClaims ) then
			for i, statement in ipairs( dateClaims ) do
				local parsedTime = context.parseTimeFromSnak( statement.mainsnak );
				if ( parsedTime ) then
					return parsedTime;
				end
			end
		end
	end

	-- TODO: check other "end" properties

	-- no death day
	return os.time();
end

function getFlag( context, entityId, actualDate )
	local flags = mw.loadData('Module:Wikidata:Dictionary/Flags');
	local countryFlags = flags[ entityId ];
	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

function p.formatCountryClaimWithFlag( context, options, statement )
	if (not context) then error('context not specified') end;
	if (not options) then error('options not specified') end;
	if (not options.entity) then error('options.entity is missing') end;
	if (not statement) then error('statement not specified') end;

	local flag = nil;
	if ( statement.mainsnak and statement.mainsnak.datavalue and statement.mainsnak.datavalue.value and statement.mainsnak.datavalue.value["numeric-id"] ) then
		local endDateTimestamp = calculateEndDateTimestamp( context, options, statement ) * 1000;
		flag = getFlag( context, 'Q' .. statement.mainsnak.datavalue.value["numeric-id"], endDateTimestamp );
	end

	if ( flag ) then
		return flag .. '&nbsp;<span class="country-name">' .. context.formatStatementDefault( context, options, statement ) .. '</span>';
	end

	return '<span class="country-name">' .. context.formatStatementDefault( context, options, statement ) .. '</span>';
end

return p;