local p = {}
-- Sekalaisia funktioita Wikidatan ja suomenkielisen Wikipedian yhteensopivuuden edistämiseksi

p.defaultDateFormat = {
	[ 7] =  {'[[Y-"luku eaa."]]', '[["ensimmäinen vuosisata eaa."]]'},
	[ 8] =  {'[[Y-"luku eaa."]]', '[[Y-"vuosikymmen eaa."]]'},
	[ 9] = '[[Y" eaa."]]',
	[10] = '[[F]] [[Y" eaa."]]',
	[11] = '[[j. F"ta"]] [[Y" eaa."]]',
	[12] = '[[j. F"ta"]] [[Y" eaa."]] "kello" H',
	[13] = '[[j. F"ta"]] [[Y" eaa."]] "kello" H.i',
	[14] = '[[j. F"ta"]] [[Y" eaa."]] "kello" H.i.s',
	functions = {
		[7] = function (year)
			return (year == 0) and 2 or 1
		end,
		[8] = function (year)
			return (year % 100 == 0) and 2 or 1
		end
	},
	check = function (self, object, lang, bce)
		local format = self[object.precision]
		if object.precision == 7 then
			object.time = object.time..' -100 years'
		end
		if type(format) == 'table' then
			format = format[
				self.functions[object.precision](
					tonumber(lang:formatDate('Y', object.time))
				)
			]
		end
		return bce == 0 and string.gsub(format, ' eaa.', '') or format
	end
}
p.calendar = {
	jul = 'http://www.wikidata.org/entity/Q1985786',
	greg = 'http://www.wikidata.org/entity/Q1985727',
	check = function (self, object, calendar)
		if type(self[calendar]) == 'string' then
			if object.calendarmodel == self[calendar] then
				return object.time
			end
		else
			return object.time
		end
	end
}

function p.getDate(frame)
	local lang = mw.getContentLanguage()
	local format = { [0] = frame:getArgument('format'):expand() }
	local calendar = frame:getArgument('calendar'):expand()
	local property = frame.args[1]
	local entity = mw.wikibase.getEntity(frame.args[2])
	if entity and entity.claims and entity.claims[property] then
		local statements = entity.claims[property]
		local date = {}
		for k, v in ipairs(statements) do
			if v.mainsnak.datavalue
			   and v.rank ~= 'deprecated'
			   and p.calendar:check(v.mainsnak.datavalue.value, calendar) then
			   	if v.rank == 'preferred' then
			   		date = { v.mainsnak.datavalue.value }
			   		break
			   	end
			   	table.insert(date, v.mainsnak.datavalue.value)
			end
		end
		for k, v in ipairs(date) do
			local bce
			v.time, bce = string.gsub(v.time, '^%-', '+')
			v.time = string.gsub(v.time, '%-00', '-01')
			if format[0] then
				format[k] = format[0]
			else
				format[k] = p.defaultDateFormat:check(v, lang, bce)
				bce = false
			end
			format[k] = string.gsub(format[k], 'Y', tonumber(lang:formatDate('Y', v.time))
				.. (bce == 1 and ' "eaa".' or ''))
			date[k] = lang:formatDate(format[k], v.time)
		end
		return table.concat(date, ', ')
	end
end

return p