--require "strict"

local p = {}

local lib = require 'Module:Wikidata/lib'
local Formatters = require 'Module:Wikidata/Formatters'

local function getValues(qualifiers)
	local Values = {}
	if qualifiers then
		for key, array in pairs(lib.props) do
			for _, prop in ipairs(array) do
				for _, snak in ipairs(qualifiers[prop] or {}) do
					if lib.IsSnakValue(snak) then
						Values[key] = Formatters.getRawValue(snak)
						break
					end
				end
			end
		end
	end
	return Values
end

function p.isCompleteStatement(statement)
	local Values = getValues(statement.qualifiers)
	return (Values.begin or Values.ending) and true
end

function p.mayCompareStatement(statement)
	return true
end

function p.compareStatements(first, second)
	local FirstValues = getValues(first.qualifiers)
	local SecondValues = getValues(second.qualifiers)
	if FirstValues.begin and SecondValues.begin then
		if FirstValues.begin ~= SecondValues.begin then
			return lib.simpleCompare(FirstValues.begin, SecondValues.begin)
		end
		if FirstValues.ending and SecondValues.ending then
			return lib.simpleCompare(FirstValues.ending, SecondValues.ending)
		end
		if FirstValues.ending then
			return -1
		elseif SecondValues.ending then
			return 1
		else
			return 0
		end
	end
	if FirstValues.ending and SecondValues.ending then
		if FirstValues.ending == SecondValues.ending then
			if FirstValues.begin then
				return 1
			elseif SecondValues.begin then
				return -1
			else
				return 0
			end
		end
	end
	if FirstValues.begin and SecondValues.ending then
		return lib.simpleCompare(FirstValues.begin, SecondValues.ending)
	end
	if FirstValues.ending and SecondValues.begin then
		if FirstValues.ending > SecondValues.begin then
			return 1
		else
			return -1
		end
	end
	return lib.simpleCompare(FirstValues.ending, SecondValues.ending)
end

return p