local getArgs = require('Module:Arguments').getArgs
local randomModule = require('Module:Random')
local yesno = require('Module:Yesno')
local slideshowModule = require('Module:Random slideshow')

p = {}

local function wikiError(message)
	return mw.html.create('div'):addClass('error'):wikitext(message)
end

-- Extracts dates and custom images
local function extractDatesAndImages(args)
	local dates = {}
	local images = {}
	for key, value in pairs(args) do
		if value and type(key) == "number" then
			table.insert(dates, value)
		elseif string.sub(key, 1, 1) == "i" then
			local num = string.sub(key, 2)
			local title = args["title" .. num]
			local credit = args["credit" .. num]
			local caption = args["caption" .. num]
			local image = {
				file = value,
				title = title,
				credit = credit,
				caption = caption
			}
			table.insert(images, image)
		end
	end
	return dates, images
end

local function getDefaultMoreLink(frame)
	local title = mw.title.getCurrentTitle()
	return "[[" .. title.prefixedText .. "/Selected picture|More selected pictures...]]"
end

local function getPortalPotdText(frame, potdDate, more)
	return frame:expandTemplate{
		title = "Portal POTD",
		args = {
			potdDate,
			["more"] = more
		}
	}
end

local function formatPotdText(titleText, creditText, captionText)
	local root = mw.html.create("div")
		:attr("class", "center")
		:attr("style", "font-size:107%;")
	local titleCredit = root:tag("div")
		:attr("style", "margin: 0.6em 0.25em 0.85em;")
	titleCredit:tag("div")
		:attr("style", "font-size: large;")
		:wikitext(titleText)
	titleCredit:tag("small"):wikitext(creditText)
	root:tag("div")
		:attr("style", "text-align: left;")
		:wikitext(captionText)
	if yesno(more, true)
	then
		root:tag('div')
			:attr("class", "noprint")
			:attr("style", "padding:0.7em 0.9em 0.7em 0.2em; font-weight:bold; width:100%; text-align:right;")
			:wikitext(more)
	end
	return tostring(root)
end

local function formatFile(filename)
	local html = mw.html.create('div')
		:attr("class", "center")
		:wikitext("[[File:" .. filename .. "|200px]]")
	return tostring(html)
end

-- Extract value named "paramName" from a subpage of [[Template:POTD]]
local function getPotdPart(frame, potdSubpage, paramName)
	return frame:expandTemplate{
		title = potdSubpage,
		args = { paramName }
	}
end

local function getPotdText(frame, potdDate, more)
	local titleText = getPotdPart(frame, "POTD/" .. potdDate, "title")
	local creditText = getPotdPart(frame, "POTD/" .. potdDate, "credit")
	local captionText = getPotdPart(frame, "POTD/" .. potdDate, "caption")
	return formatPotdText(titleText, creditText, captionText)
end

local function makeSlideShowArgs(frame, dates, images, more, limit)
	local slideShowArgs = {}
	local randomDates = randomModule.main('array', {t=dates, limit=limit})
	for _i, potdDate in ipairs(randomDates) do
		local image = getPotdPart(frame, "POTD/" .. potdDate, "image")
		local text = getPotdText(frame, potdDate, more)
		table.insert(slideShowArgs, image)
		table.insert(slideShowArgs, text)
	end
	local randomImages = randomModule.main('array', {t=images, limit=limit})
	for key, image in pairs(randomImages) do
		table.insert(slideShowArgs, image['file'])
		local text = formatPotdText(image['title'], image['credit'], image['caption'])
		table.insert(slideShowArgs, text)
	end
	return slideShowArgs
end

-- Create a list gallery of all passed images
local function gallery(frame)
	local args = getArgs(frame)
	local dates, images = extractDatesAndImages(args)
	local texts = {}
	for key, value in pairs(dates) do
		table.insert(texts,	"[[Template:POTD/" .. value .. "]]\n\n" .. getPortalPotdText(frame, value, "no"))
	end
	for key, image in pairs(images) do
		local bottomText = formatPotdText(image['title'], image['credit'], image['caption'])
		table.insert(texts, formatFile(image['file']) .. "\n\n" .. bottomText)
	end
	return table.concat(texts, "\n----\n")
end

-- Create a slideshow of passed images using [[Module:Random slideshow]]
local function slideShow(frame)
	local args = getArgs(frame)
	local more = args["more"] or getDefaultMoreLink(frame)
	local dates, images = extractDatesAndImages(args)
	local limit = 15

	local galleryArgs = makeSlideShowArgs(frame, dates, images, more, limit)
	local slideShow = slideshowModule._main(galleryArgs, false)
	return frame:extensionTag{ name='templatestyles', args = { src='Random slideshow/styles.css'} }
		.. frame:preprocess(slideShow)
end

function main(frame)
	local title = mw.title.getCurrentTitle()
	if title.isSubpage
	then
		return gallery(frame)
	else
		return slideShow(frame)
	end
end

p.main = main
p.slideShow = slideShow
p.gallery = gallery

return p