--[[
Devolve uma string de coordenadas compatível com Predefinição:Coor dms/str (que pode ser usada em {{Coor dms}} e várias {{Info/...}}) construída com dados da Wikidata.

Uso: {{#invoke:CoordStrWD|coord_str| <string_def> | <get_wikidata> }}

Só vai buscar dados ao Wikidata se get_wikidata tiver algum valor (qualquer um) e string_def não for indicada. Se string_def for indicada, é ela que é devolvida.
--]]

local coord = {}

local function getWdObj( qid)
	if qid then
		qid = mw.text.trim(qid);
	end
	if qid == '' then
		entity = mw.wikibase.getEntityObject();
	else
		entity = mw.wikibase.getEntityObject(qid);
	end

	if entity == nil then
		return nil;
	end

	entity = entity.claims;
	if entity == nil then
		return nil;
	end

	entity = entity['P625'];
	if entity == nil then
		return nil;
	end

	entity = entity[1];
	if entity == nil then
		return nil;
	end

	entity = entity.mainsnak;
	if entity == nil then
		return nil;
	end

	entity = entity.datavalue;
	if entity == nil then
		return nil;
	end

	if entity.type ~= 'globecoordinate' then
		return nil;
	end

	entity = entity.value;
	if entity == nil then
		return nil;
	end

	return entity;
end

local function grausminseg( vdec, neg, pos)
	if vdec == nil then
		return '';
	end

	local graus = math.floor(math.abs(vdec));
	local minx = 60 * (math.abs(vdec) - graus);
	local minut = math.floor(minx);
	local seg = math.floor(60 * (minx - minut) + 0.499999);
	if seg > 59 then
		seg = 0;
		minut = minut +1;
	end
	if minut > 60 then
		minut = 0;
		graus = graus + 1;
	end
	
	if string.len(graus) < 2 then
		graus = '0'..graus;
	end
	if string.len(minut) < 2 then
		minut = '0'..minut;
	end
	if string.len(seg) < 2 then
		seg = '0'..seg;
	end
	if vdec < 0 then
		vdec = neg;
	else
		vdec = pos;
	end

	return graus..'º'..minut.."'"..seg..'"'..vdec;
end

function coord.coord_str( frame)

	local vdef = frame.args[1] or '';
	vdef = mw.text.trim(vdef);
	if vdef ~= '' then
		return vdef;
	end

	local getWD = frame.args[2];
	getWD = mw.text.trim(getWD) or '';
	if getWD == '' then
		return '';
	end

	local qid = frame.args[3] or '';
	local entity = getWdObj( qid);
	if entity == nil then
		return '';
	end
	
	local lat = grausminseg( entity.latitude, 'S', 'N');
	if lat == '' then
		return '';
	end

	return lat..' '..grausminseg( entity.longitude, 'W', 'E');
end

return coord;