Module:Availability

From SPCodex, The Smashing Pumpkins wiki
Revision as of 18:30, 10 June 2020 by MusikAnimal (talk | contribs)

This module implements the {{availability}} template, which is placed on every song page. This generates the "Availability" and "Tour stats" sections, as applicable.


local p = {}

local function pairsByKeys (t, f)
	local a = {}
	for n in pairs(t) do table.insert(a, n) end
	table.sort(a, f)
	local i = 0      -- iterator variable
	local iter = function ()   -- iterator function
		i = i + 1
		if a[i] == nil then return nil
		else return a[i], t[a[i]]
		end
	end
	return iter
end

local function dateFormat(str, precision)
	if precision == '2' then
		return string.sub(str, 0, -3) .. 'xx'
	elseif precision == '3' then
		return string.sub(str, 0, -6) .. 'xx-xx'
	else
		return str
	end
end

function p._main(song)
	local cargo = mw.ext.cargo
	local albums = cargo.query(
		'track_listings, albums, releases',
		"track_listings._pageName=title, releases.release_date=date, release_date__precision=precision, albums.type=type",
		{
			where = "releases.release_date != '' AND song = \"" .. song .. '"',
			join = 'track_listings._pageName=albums._pageName,albums.name=releases.work',
			groupBy = 'track_listings.work',
			orderBy = 'releases.release_date ASC'
		}
	)
	local songs = cargo.query(
		'track_listings, songs, releases',
		"track_listings._pageName=title, releases.release_date=date, release_date__precision=precision, songs.type=type",
		{
			where = "releases.release_date != '' AND song = \"" .. song .. '"',
			join = 'track_listings._pageName=songs._pageName,songs.name=releases.work',
			groupBy = 'track_listings.work',
			orderBy = 'releases.release_date ASC'
		}
	)

	local releasesByDate = {}

	for r = 1, #songs do
		releasesByDate[songs[r]['date']] = songs[r]
	end
	for r = 1, #albums do
		releasesByDate[albums[r]['date']] = albums[r]
	end
	
	local root = mw.html.create()
	local tableRoot = root:tag('table')
	tableRoot:addClass('mw-datatable sortable jquery-tablesorter')
	local headerRow = tableRoot:tag('tr')
	headerRow:tag('th')
		:addClass('headerSort')
		:wikitext('Title')
	headerRow:tag('th')
		:addClass('headerSort')
		:wikitext('Release date')
	headerRow:tag('th')
		:addClass('headerSort')
		:wikitext('Type')

	for _date, release in pairsByKeys(releasesByDate) do
		local row = tableRoot:tag('tr')
		mw.log(release['title'])
		mw.log(release['date'])
		row:tag('td'):wikitext('[[' .. release['title'] .. ']]')
		row:tag('td'):wikitext(dateFormat(release['date'], release['precision']))
		-- row:tag('td'):wikitext(typeFormat(release['type']))
	end
	
	return tostring(root)
end

function p.main(frame)
	local song = frame.args[1]
	return p._main(song)
end

return p