local p = {}

-- module local variables
local wiki = 
{
	langcode = mw.language.getContentLanguage().code
}

local i18n = {
	["errors"] = {
		["property-not-found"] = "Propietat no trobada.",
		["entity-not-found"] = "Entitat no trobada.",
		["unknown-claim-type"] = "Tipus d'afirmació (claim) desconegut.",
		["unknown-entity-type"] = "Tipus d'entitat desconegut.",
		["qualifier-not-found"] = "Qualificador no trobat.",
		["site-not-found"] = "Projecte Wikimedia no trobat.",
		["unknown-datetime-format"] = "Format data/horari desconegut.",
		["local-article-not-found"] = "L'article encara no està disponible en aquest wiki"
	},
	["datetime"] =
	{
		-- $1 is a placeholder for the actual number
		[0] = "$1 mila milioi urte",	-- precision: billion years
		[1] = "$100 milioi urte",	-- precision: hundred million years
		[2] = "$10 milioi urte",	-- precision: ten million years
		[3] = "$1 milioi urte",	-- precision: million years
		[4] = "$100.000 urte",		-- precision: hundred thousand years
		[5] = "$10.000 urte",		-- precision: ten thousand years
		[8] = "$1(e)ko hamarkada",		-- precision: decade
		-- the following use the format of #time parser function
		[6] = "xrY milurtekoa",	 	-- precision: millennium
		[7] = "xrY. mendea",			-- precision: century
		[9]  = "Y",					-- precision: year, 
		[10] = "Y(eko) F",				-- precision: month
		[11] = "Y-m-d",				-- precision: day
		[12] = "Y-m-d, ga",			-- precision: hour
		[13] = "Y-m-d g:ia",		-- precision: minute
		[14] = "Y-m-d g:i:sa",		-- precision: second
		["beforenow"] = "duela $1",	-- how to format negative numbers for precisions 0 to 5
		["afternow"] = "$1 barru",	-- how to format positive numbers for precisions 0 to 5
		["bc"] = '$1 K. a.',			-- how print negative years
		["ad"] = "$1"				-- how print positive years
	},
	["monolingualtext"] = '<span lang="%language">%text</span>',
	["warnDump"] = "[[Category:Funció Dump del mòdul Wikidata]]"
}

-- Local grammatical cases
local function case(word, case)
	if word == nil or word == '' then return end
	
	if case == "singularra" then
		return require("Module:Declension").absolutive_singular(word)
	end
	
	if case == "ergatiboa" then
		return require("Module:Declension").ergative(word)
	end
	
	return word
end

local function printDatavalueString(data, parameter)
	if parameter == 'weblink' then 
		return '[' .. data ..  ' ' ..  mw.text.split(data, '//' )[2] .. ']'
	elseif mw.ustring.find((parameter or ''), '$1', 1, true) then -- formatting = a pattern
		return mw.ustring.gsub(parameter, '$1', data) .. '' -- hack to get only the first result of the function
	else
		return data
	end
end

local function printDatavalueCoordinate(data, parameter)
	local globetable = {Q2 = 'earth', Q111 = 'mars', Q405 = 'moon'}
	
	if parameter == 'latitude' then
		return data.latitude
	elseif parameter == 'longitude' then
		return data.longitude
	elseif parameter == 'dimension' then
		return data.dimension
	else
		if data.globe == '' or data.globe == nil then
			return 'earth'
		else
			local globenum = mw.text.split(data.globe, 'entity/')[2] -- http://www.wikidata.org/wiki/Q2
			if globetable[globenum] then 
				return globetable[globenum]
			else
				return globenum
			end
		end
	end
end

local function printDatavalueQuantity(data, parameter)
	-- exemples: 277±1 Centímetre, 1,94 metre
	local amount = data.amount
	amount = mw.ustring.gsub(amount, "%+", "")
	local sortkey = string.format("%09d", amount)
	local lang = mw.language.new(wiki.langcode)
	amount = lang:formatNum(tonumber(amount))
	return amount, sortkey
end

local function printDatavalueTime(data, parameter)
	-- Dates and times are stored in ISO 8601 format
	-- check for negative date, ex. "-0027-01-16T00:00:00Z"
	local suffix = ""
	local timestamp = data.time
	local sortkey = timestamp
	if string.sub(timestamp, 1, 1) == '-' then
		timestamp = '+' .. string.sub(timestamp, 2)
		suffix = " aC"
	elseif string.sub(timestamp, 2, 3) == '00' then
		suffix = " dC"
	end
	local function d(f, t)
		return mw.language.new(wiki.langcode):formatDate(f, t or timestamp) .. suffix
	end
	local precision = data.precision or 11
	local any = tonumber(mw.ustring.match(timestamp, "^\+?%d+"))
	local ret = ""
	
	-- precision is 10000 years or more
	if precision <= 5 then
		local factor = 10 ^ ((5 - precision) + 4)
		local y2 = math.ceil(math.abs(any) / factor)
		local relative = mw.ustring.gsub(i18n.datetime[precision], "$1", tostring(y2))
		if suffix == " aC" then
			ret = mw.ustring.gsub(i18n.datetime.beforenow, "$1", relative)
		else
			ret = mw.ustring.gsub(i18n.datetime.afternow, "$1", relative)
		end
	-- precision is millennia, centuries or decades
	elseif precision == 6 then
		ret = d('xrY". milurtekoa"', string.format("%04d", tostring(math.floor((math.abs(any) - 1) / 1000) + 1)))
	elseif precision == 7 then -- segles
		ret = d('xrY". mendea" ', string.format("%04d", tostring(math.floor((math.abs(any) - 1) / 100) + 1)))
	elseif precision == 8 then
		ret = mw.ustring.gsub(i18n.datetime[8], "$1", tostring(math.floor(math.abs(any) / 10) * 10)) .. suffix
	-- precision is year
	elseif parameter == 'year' or precision == 9 then
		ret = tostring(any) .. suffix
	-- precision is month
	elseif precision == 10 then
		timestamp = timestamp .. " + 1 day" -- formatDate yyyy-mm-00 returns the previous month
		ret, _ = string.gsub(d("F Y"), " 0+", " ") -- supress leading zeros in year
	elseif parameter and parameter ~= "table" then
		ret, _ = string.gsub(d(parameter), " 0+", " ")
	else
		ret = require("Module:Date").genitive_year(any) .. d(' F"ren" j')
	end
	return ret, sortkey
end

local function printDatavalueEntity(data, parameters)
	local entityId = "Q" .. tostring(data['numeric-id'])
	local label = mw.wikibase.label(entityId)
	local sitelink = mw.wikibase.sitelink(entityId)
	local parameter = parameters.formatting
	if parameter == 'raw' then 
		return entityId
	elseif parameter == 'label' then
		return (label or entityId)
	elseif parameter == 'sitelink' then
		return (sitelink or 'wikidata:' .. entityId)
	else
		local labelcase = label or sitelink
		if parameters.case then
			labelcase = case(labelcase, parameters.case)
		end
		if sitelink then
			return '[[' .. sitelink .. '|' .. labelcase .. ']]', labelcase
		elseif label and parameter == 'internallink' then
			return '[[' .. label .. '|' .. labelcase .. ']]', labelcase
		else
			return '[[wikidata:' .. entityId .. '|' .. (labelcase or entityId) .. ']]', labelcase or entityId
		end
	end
end

local function printDatavalueMonolingualText(data, parameter)
	-- data fields: language [string], text [string]
	local result = nil
	if parameter == "language" or parameter == "text" then
		result = data[parameter]
	elseif parameter then
		if data["language"] == wiki.langcode then
			if parameter then
				result = printDatavalueString(data["text"], parameter)
			else
				result = data["text"]
			end
		end
	else
		result = mw.ustring.gsub(mw.ustring.gsub(i18n.monolingualtext, "%%language", data["language"]), "%%text", data["text"])
	end
	return result
end

local function printError(key)
    return '<span class="error">' .. i18n.errors[key] .. '</span>'
end

local function findClaims(entity, property)
	if not property or not entity or not entity.claims then return end
	
	if mw.ustring.match(property, "^P%d+$") then
		-- if the property is given by an id (P..) access the claim list by this id
		return entity.claims[property]
	else
		property = mw.wikibase.resolvePropertyId(property)
		if not property then return end

		return entity.claims[property]
	end
end

local function getSnakValue(snak, parameters)
	local parameter = parameters.formatting
	if snak.snaktype == 'value' then
		-- call the respective snak parser
		if snak.datavalue.type == "string" then
			return printDatavalueString(snak.datavalue.value, parameter)
		elseif snak.datavalue.type == "globecoordinate" then
			return printDatavalueCoordinate(snak.datavalue.value, parameter)
		elseif snak.datavalue.type == "quantity" then
			return printDatavalueQuantity(snak.datavalue.value, parameter)
		elseif snak.datavalue.type == "time" then
			return printDatavalueTime(snak.datavalue.value, parameter)
		elseif snak.datavalue.type == 'wikibase-entityid' then
			return printDatavalueEntity(snak.datavalue.value, parameters)
		elseif snak.datavalue.type == 'monolingualtext' then
			return printDatavalueMonolingualText(snak.datavalue.value, parameter)
		end
	end
	return mw.wikibase.renderSnak(snak)
end

local function getQualifierSnak(claim, qualifierId, parameters)
	-- a "snak" is Wikidata terminology for a typed key/value pair
	-- a claim consists of a main snak holding the main information of this claim,
	-- as well as a list of attribute snaks and a list of references snaks
	if qualifierId then
		-- search the attribute snak with the given qualifier as key
		if claim.qualifiers then
			local qualifier = claim.qualifiers[qualifierId]
			if qualifier then
				-- iterate over monolingualtext qualifiers to get local language
				for idx in pairs(qualifier) do
					if qualifier[idx].datavalue.value.language == wiki.langcode then
						return qualifier[idx]
					end
				end
				if parameters.list then
					return qualifier
				else
					return qualifier[1]
				end
			end
		end
		return nil, printError("qualifier-not-found")
	else
		-- otherwise return the main snak
		return claim.mainsnak
	end
end

local function getValueOfClaim(claim, qualifierId, parameters)
	local error
	local snak
	snak, error = getQualifierSnak(claim, qualifierId, parameters)
	if not snak then
		return nil, nil, error
	elseif snak[1] then -- a multi qualifier
		local result = {}
		local sortkey = {}
		for idx in pairs(snak) do
			result[#result + 1], sortkey[#sortkey + 1] = getSnakValue(snak[idx], parameters)
		end
		return mw.text.listToText(result, parameters.qseparator, parameters.qconjunction), sortkey[1]
	else -- a property or a qualifier
		return getSnakValue(snak, parameters)
	end
end

-- Return the site link (for the current site) for a given data item.
function p.getSiteLink(frame)
    if frame.args[1] == nil then
        entity = mw.wikibase.getEntityObject()
        if not entity then
        	return nil
        end
        id = entity.id
    else
        id = frame.args[1]
    end
 
    return mw.wikibase.sitelink(id)
end

-- A la consola de depuració useu: =p.proves({item="Q...", property="P...", ...})
function p.proves(args)
	return _main(args)
end

function p.claim(frame)
	local args = frame.args
	return _main(args)
end

function _main(args)
	--If a value is already set, use it
	if args.value and args.value ~= '' then
		return args.value
	end
	
	-- arguments
	local property = args["property"] or ""
	local id = args["item"]; if id == "" then id = nil end
	local qualifierId = {}
	qualifierId[1] = args["qualifier"] or args["qualifierProperty"] -- compatibilitat de transició
	for i = 2, 9 do
		qualifierId[i] = args["qualifier" .. i]
	end
	local parameter = args["formatting"] or ''; if parameter == "" then parameter = nil end
	local case = args.case
	local list = args["list"] or true; if list == "false" then list = false end
	local sorting = args.tablesort
	local separator = args.separator
	local conjunction = args.conjunction
	local rowformat = args.rowformat
	local showerrors = args["showerrors"]
	local default = args["default"]
	
	property = property:gsub("^p(%d)", "P%1")
	if qualifierId[1] then qualifierId[1] = qualifierId[1]:gsub("^p(%d)", "P%1") end
	if not parameter and args["rank"] == "ca" then parameter = "ca" end -- compatibilitat de transició
	if args["rank"] and args["rank"] ~= '' then list = false end -- compatibilitat de transició
	local parameters = {["formatting"] = parameter, ["list"] = list, ["sorting"] = sorting, ["case"] = case,
		["separator"] = separator, ["conjunction"] = conjunction, ["qseparator"] = separator, ["qconjunction"] = conjunction}
	local preformat = ""
	local postformat = ""
	if parameters.formatting == "table" then
		parameters.separator = parameters.separator or "<br />"
		parameters.conjunction = parameters.conjunction or "<br />"
		parameters.qseparator = ", "
		parameters.qconjunction = ", "
		if not rowformat then
			rowformat = "$0 ($1"
			for i = 2, 9 do
				if qualifierId[i] then
					rowformat = rowformat .. ", $" .. i
				end
			end
			rowformat = rowformat .. ")"
		elseif mw.ustring.find(rowformat, "^[*#]") then
			parameters.separator = "</li><li>"
			parameters.conjunction = "</li><li>"
			if mw.ustring.match(rowformat, "^[*#]") == "*" then
				preformat = "<ul><li>"
				postformat = "</li></ul>"
			else
				preformat = "<ol><li>"
				postformat = "</li></ol>"
			end
			rowformat = mw.ustring.gsub(rowformat, "^[*#] ?", "")
		end
	end
	if default then showerrors = nil end
	
	-- get wikidata entity
	local entity = mw.wikibase.getEntityObject(id)
	if not entity then
		if showerrors then return printError("entity-not-found") else return default end
	end
	-- fetch the first claim of satisfying the given property
	local claims = findClaims(entity, property)
	if not claims or not claims[1] then
		if showerrors then return printError("property-not-found") else return default end
	end
	
	-- get initial sort indices
	local sortindices = {}
	for idx in pairs(claims) do
		sortindices[#sortindices + 1] = idx
	end
	-- sort by claim rank
	local comparator = function(a, b)
		local rankmap = { deprecated = 2, normal = 1, preferred = 0 }
		local ranka = rankmap[claims[a].rank or "normal"] ..  string.format("%08d", a)
		local rankb = rankmap[claims[b].rank or "normal"] ..  string.format("%08d", b)
		return ranka < rankb
	end
	table.sort(sortindices, comparator)
	
	local result
	local error
	if parameters.list or parameters.formatting == "table" then
		-- iterate over all elements and return their value (if existing)
		local value, valueq
		local sortkey, sortkeyq
		local values = {}
		local sortkeys = {}
		for idx in pairs(claims) do
			values[#values + 1] = {}
			sortkeys[#sortkeys + 1] = {}
			local claim = claims[sortindices[idx]]
			if parameters.formatting == "table" then
				value, sortkey, error =  getValueOfClaim(claim, nil, parameters)
				for i, qual in ipairs(qualifierId) do
					valueq, sortkeyq, _ =  getValueOfClaim(claim, qual, parameters)
					values[#values]["col" .. i] = valueq
					sortkeys[#sortkeys]["col" .. i] = sortkeyq or valueq
				end
			else
				value, sortkey, error =  getValueOfClaim(claim, qualifierId[1], parameters)
			end
			if not value and showerrors then value = error end
			
			values[#values]["col0"] = value
			sortkeys[#sortkeys]["col0"] = sortkey or value
		end
		-- sort and format results
		if parameters.sorting then
			local comparator = function(a, b)
				valuea = sortkeys[a]["col" .. parameters.sorting] or ''
				valueb = sortkeys[b]["col" .. parameters.sorting] or ''
				return valuea < valueb
			end
			table.sort(sortindices, comparator)
		end
		result = {}
		for idx in pairs(claims) do
			local valuerow = values[sortindices[idx]]
			value = valuerow["col0"]
			if parameters.formatting == "table" then
				value = mw.ustring.gsub(rowformat, "$0", value)
				for i, _ in ipairs(qualifierId) do
					valueq = valuerow["col" .. i]
					if args["rowsubformat" .. i] and valueq then
						valueq = mw.ustring.gsub(args["rowsubformat" .. i], "$" .. i, valueq)
					end
					value = mw.ustring.gsub(value, "$" .. i, valueq or '')
				end
			end
			
			result[#result + 1] = value
		end
		result = preformat .. mw.text.listToText(result, parameters.separator, parameters.conjunction) .. postformat
	else
		-- return first element	
		local claim = claims[sortindices[1]]
		result, _, error = getValueOfClaim(claim, qualifierId[1], parameters)
	end
	
	-- This is used to get the unit name for a numeric value
	local suffix = ""
	if parameters.formatting == "unit" or parameters.formatting == "unitcode" then
		local result_unit = entity:formatPropertyValues(property, mw.wikibase.entity.claimRanks).value
		if claims[1] and claims[1].mainsnak.snaktype == "value" and claims[1].mainsnak.datavalue.type == "quantity" then
			if mw.ustring.find(result_unit, " ") then
				local unit_label = mw.ustring.sub(result_unit, mw.ustring.find(result_unit, " ")+1, -1)
				-- get the url for the unit entry on Wikidata:
				local unitID = claims[1].mainsnak.datavalue.value.unit
				-- and just return the last bit from "Q" to the end (which is the QID):
				unitID = mw.ustring.sub(unitID, mw.ustring.find(unitID, "Q"), -1)
				suffix = " " .. require("Module:Wikidata/Units").getUnit(result, unit_label, unitID, parameters.formatting == "unitcode")
			end
		end
	end

	if result then return result .. suffix else
		if showerrors then return error else return default end
	end
end

-- Return the statements with a format
function p.formatStatements(frame)
	return p.claim(frame) -- compatibilitat de transició
end

--Return the qualifiers with a format
function p.formatQualifiers(frame)
	return p.claim(frame) -- compatibilitat de transició
end

-- This is used to get the TA98 (Terminologia Anatomica first edition 1998) values like 'A01.1.00.005' (property P1323)
-- which are then linked to http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/01.1.00.005%20Entity%20TA98%20EN.htm
-- uses the newer mw.wikibase calls instead of directly using the snaks
-- formatPropertyValues returns a table with the P1323 values concatenated with ", " so we have to split them out into a table in order to construct the return string
p.getTAValue = function(frame)
    local ent = mw.wikibase.getEntityObject()
    local props = ent:formatPropertyValues('P1323')
    local out = {}
    local t = {}
    for k, v in pairs(props) do
        if k == 'value' then
            t = mw.text.split( v, ", ")
            for k2, v2 in pairs(t) do
                out[#out + 1] = "[http://www.unifr.ch/ifaa/Public/EntryPage/TA98%20Tree/Entity%20TA98%20EN/" .. string.sub(v2, 2) .. "%20Entity%20TA98%20EN.htm " .. v2 .. "]"
            end
        end
    end
    local ret = table.concat(out, "<br> ")
    if #ret == 0 then
        ret = "Invalid TA"
    end
    return ret
end

-- look into entity object
function p.ViewSomething(frame)
	local f = (frame.args[1] or frame.args.item) and frame or frame:getParent()
	local id = f.args.item
	if id and (#id == 0) then
		id = nil
	end
	local data = mw.wikibase.getEntityObject(id)
	if not data then
		return nil
	end

	local i = 1
	while true do
		local index = f.args[i]
		if not index then
			if type(data) == "table" then
				return mw.text.jsonEncode(data, mw.text.JSON_PRESERVE_KEYS + mw.text.JSON_PRETTY)
			else
				return tostring(data)
			end
		end
		
		data = data[index] or data[tonumber(index)]
		if not data then
			return
		end
		
		i = i + 1
	end
end

-- Dump data tree structure
-- From pl:Module:Wikidane, by User:Paweł Ziemian
-- Funció pensada com a eina d'ajuda en previsualització.
function p.Dump(frame)
	local data = mw.wikibase.getEntityObject()
	if not data then
		return i18n.warnDump
	end
	
	local f = frame.args[1] and frame or frame:getParent()

	local i = 1
	while true do
		local index = f.args[i]
		if not index then
			return "<pre>" .. mw.dumpObject(data) .. "</pre>" .. i18n.warnDump
		end
		
		data = data[index] or data[tonumber(index)]
		if not data then
			return i18n.warnDump
		end
		
		i = i + 1
	end
end

-- Look into entity object
-- From pl:Module:Wikidane, function V, by User:Paweł Ziemian
function p.getEntityFromTree(frame)
	local data = mw.wikibase.getEntityObject()
	if not data then
		return nil
	end
	
	local f = frame.args[1] and frame or frame:getParent()
	
	local i = 1
	while true do
		local index = f.args[i]
		if not index then
			return tostring(data)
		end
		
		data = data[index] or data[tonumber(index)]
		if not data then
			return
		end
		
		i = i + 1
	end
end

return p