Documentation for this module may be created at Module:Meshblocks/doc

local MeshblocksToStreets = require( 'Module:MeshblocksToStreets' )
local MeshblockData = require( 'Module:MeshblockData' )
local p = {}

-- Kudos: https://stackoverflow.com/a/20282998
local hexToChar = function(x)
	return string.char(tonumber(x, 16))
end

p.list = function()
	local meshblocks = {}
	for k,meshblock in pairs( MeshblocksToStreets ) do
		if meshblock.MB_CODE16 ~= nil then
			meshblocks[ '_' .. meshblock.MB_CODE16 ] = 'Meshblock ' .. meshblock.MB_CODE16
		end
	end
	local out = '<ol style="columns:16em auto">'
	for k,v in pairs( meshblocks ) do
		out = out .. '<li>[[' .. v ..']]</li>'
	end
	out = out .. '</ol>'
	return out
end

p.single = function( frame )
	local title = mw.title.getCurrentTitle().text
	if frame.args ~= nil and frame.args.title ~= nil then
		title = frame.args.title
	end
	local meshblockId = string.sub( title, 11 )
	local streets = {}
	for k,meshblock in pairs( MeshblocksToStreets ) do
		if meshblock.MB_CODE16 ~= nil and tostring(meshblock.MB_CODE16) == meshblockId then
			streets[ meshblock.name ] = meshblock.name
		end
	end

	local data = MeshblockData[ meshblockId ]

	local query = 'SELECT ?item ?label ?location ?image ?commonscat ?articlename ?sitelink ?inherit WHERE {'
		.. 'SERVICE wikibase:around {'
		.. '  ?item wdt:P625 ?location . ' 
		.. '  bd:serviceParam wikibase:center "Point(' .. data.WGS84_long .. ' ' .. data.WGS84_lat .. ')"^^geo:wktLiteral . '
		.. '  bd:serviceParam wikibase:radius "0.2" '
		.. '}'
		.. 'OPTIONAL { ?item wdt:P18 ?image }'
		.. 'OPTIONAL { ?item wdt:P373 ?commonscat }' 
		.. 'OPTIONAL { ?item wdt:P2618 ?inherit }' 
		.. 'SERVICE wikibase:label { bd:serviceParam wikibase:language "en" . ?item rdfs:label ?label } .'
		.. 'OPTIONAL {'
		.. '  ?sitelink schema:about ?item;'
		.. '  schema:isPartOf <https://en.wikipedia.org/>;'
		.. '  schema:name ?articlename'
		.. '}'
		.. '}'
	local res = mw.ext.UnlinkedWikibase.query( query )
	local mapPoints = ''
	local wikipedias = {}
	local inherits = {}
	local images = {}
	if res ~= nil and res.results ~= nil and res.results.bindings ~= nil then
		for k,v in pairs( res.results.bindings ) do
			-- @OTOD Just query the separate coords instead of doing WKT string stuff.
			local wkt = v.location.value
			local coordParts = mw.text.split( string.sub( wkt, 7, string.len( wkt ) - 1 ), ' ' )
			if #coordParts == 2 then
				mapPoints = mapPoints ..  coordParts[2] .. ',' .. coordParts[1] .. '~' .. v.label.value .. ';'
			end
			if v.articlename ~= nil then
				wikipedias[v.articlename.value] = v.articlename.value
			end
			if v.inherit ~= nil then
				inherits[v.inherit.value] = v.label.value
			end
			if v.image ~= nil then
				images[v.image.value] = v.label.value
			end
		end
	end

	local geojson = 'Meshblocks'
	local perMeshblockGeojson = mw.title.new( 'GeoJSON:' .. title  )
	mw.logObject(perMeshblockGeojson)
	mw.logObject(perMeshblockGeojson.exists)
	if perMeshblockGeojson.exists then
		geojson = title
	end
	local mapParams = {
		mapPoints,
		center = data.WGS84_lat .. ',' .. data.WGS84_long,
		geojson = geojson,
		zoom = '18',
		height = '400px'
	}
	local map = mw.getCurrentFrame():callParserFunction{ name = '#display_map', args = mapParams }
	local out = '<div class="tpl-meshblock">'
	local out = out .. map
	
	out = out .. 'This is <strong>[[meshblocks|meshblock]] "' .. meshblockId .. '"</strong>.\n\n'

	out = out .. '<div class="tpl-meshblock-boxes">'

	out = out .. '<div class="tpl-meshblock-box tpl-meshblock-abs">'
	out = out .. '<div class="tpl-meshblock-box-title">Australian Bureau of Statistics data:</div>'
	out = out .. '<div class="tpl-meshblock-box-body">\n'
	out = out .. '* Total population: ' .. data.Pop_Total .. '\n'
	out = out .. '* Area: ' .. data.AREASQKM16 .. ' km<sup>2</sup>\n\n'
	out = out .. '</div></div>'

	out = out .. '<div class="tpl-meshblock-box tpl-meshblock-links">'
	out = out .. '<div class="tpl-meshblock-box-title">Useful links:</div>'
	out = out .. '<div class="tpl-meshblock-box-body">\n'
	out = out .. '* [https://www.inaturalist.org/projects/wild-about-freo Wild About Freo] on [[File:INaturalist text logo.svg|80px|alt=iNaturalist|link=]]\n'
	out = out .. '* [https://commons.wikimedia.org/wiki/Special:UploadWizard Upload your own Fremantle photos to Wikimedia Commons]\n'
	out = out .. '* [https://www.openstreetmap.org/#map=16/-32.0555/115.7476 Edit the Fremantle map on OpenStreetMap]\n'
	out = out .. '</div></div>'

	out = out .. '</div><div class="tpl-meshblock-boxes">'
	
	out = out .. '<div class="tpl-meshblock-box tpl-meshblock-wikipedia">'
	out = out .. '<div class="tpl-meshblock-box-title">[[File:Wikipedia-logo-v2-en.svg|left|50px|link=]]Wikipedia articles about things in this area:</div>'
	out = out .. '<div class="tpl-meshblock-box-body">\n'
	for k,article in pairs( wikipedias ) do
		out = out .. '* [[wikipedia:' .. article .. '|' .. article .. ']]\n'
	end
	out = out .. '</div></div>'

	out = out .. '<div class="tpl-meshblock-box tpl-meshblock-inherit">'
	out = out .. '<div class="tpl-meshblock-box-title">State Heritage Office\'s [http://inherit.stateheritage.wa.gov.au inHerit] records in this area:</div>'
	out = out .. '<div class="tpl-meshblock-box-body">\n'
	for inheritId,label in pairs( inherits ) do
		out = out .. '* [http://inherit.stateheritage.wa.gov.au/public/p/' .. inheritId .. ' ' .. inheritId .. ' — ' .. label .. ']\n'
	end
	out = out .. '</div></div>'

	out = out .. '<div class="tpl-meshblock-box tpl-meshblock-streets">'
	out = out .. '<div class="tpl-meshblock-box-title">Learn more about the streets that pass through this area, on the Fremantle Streets project:</div>'
	out = out .. '<div class="tpl-meshblock-box-body">\n'
	for k,street in pairs( streets ) do
		out = out .. '* [[' .. street .. "]]\n"
	end
	out = out .. '</div></div>'

	out = out .. '</div><!-- End .tpl-meshblock-boxes -->'

	local galleryList = ''
	for img,label in pairs( images ) do
		local unencodedFilename = string.sub( img, 52 ):gsub( "%%(%x%x)", hexToChar )
		galleryList = galleryList .. 'File:' .. unencodedFilename .. ' | ' .. label .. '\n'
	end
	out = out .. mw.getCurrentFrame():extensionTag( 'gallery', galleryList, { mode = 'packed-hover' } )

	return out
end

-- =p.single({args={title="Meshblock 50117480000"}})
return p