local p = {}
local excerptModule = require('Module:Excerpt')
local randomModule = require('Module:Random')
local redirectModule = require('Module:Redirect')

function cleanupArgs(argsTable)
	local cleanArgs = {}
	for key, val in pairs(argsTable) do
		if type(val) == 'string' then
			val = val:match('^%s*(.-)%s*$')
			if val ~= '' then
				cleanArgs[key] = val
			end
		else
			cleanArgs[key] = val
		end
	end
	return cleanArgs
end

function normaliseCssMeasurement(input)
	local suffix = string.reverse(string.sub(string.reverse(input), 1, 2))
	if ( suffix == 'px' ) or ( suffix == 'em' ) or ( string.sub == '%' ) then
		return input
	else
		return input .. 'px'
	end
end

function isDeclined(val)
	if not val then return false end
	local declinedWords = " decline declined exclude excluded false none not no n off omit omitted remove removed "
	return string.find and true or false
end

function makeOutput
	local randomiseArgs = {	['t'] = galleryLines }
	local sortedLines = nonRandom and galleryLines or randomModule.main
	local galleryContent = table.concat
	local output = ''
	return output
end

function makeGalleryLine
	local title = mw.title.new
	local creditLine = ( credit and '' or '' )
	return title.prefixedText .. '' .. ( caption or '' ) .. creditLine
end

function makeGalleryLinesTable(args)
	local galleryLinesTable = {}
	local i = 1
	while args[i] do
		table.insert(galleryLinesTable, makeGalleryLine(args[i], args[i+1], args['credit' .. (i+1)/2] or args['크레딧' .. (i+1)/2]))
		i = i + 2
	end
	return galleryLinesTable 
end

function hasCaption(line)
	local caption = mw.ustring.match(line, ".-(.*)")
	-- require caption to exist with more than 5 characters (avoids sizes etc being mistaken for captions)
	return caption and #caption>5 and true or false
end

function extractGalleryFiles(wikitext)
	local gallery = mw.ustring.match
	if not gallery then
		return false
	end
	gallery = mw.ustring.gsub
	return mw.text.split
end

function extractRegularFiles(wikitext)
	local files = {}
	local frame = mw.getCurrentFrame
	local expand = function(template)
		return frame:preprocess(template)
	end
	for file in mw.ustring.gmatch do
		-- remove keywords that don't work in galleries
		file = mw.ustring.gsub(file, '|%s*thumb%s*([|%]])', '%1')
		file = mw.ustring.gsub(file, '|%s*thumbnail%s*([|%]])', '%1')
		file = mw.ustring.gsub(file, '|%s*left%s*([|%]])', '%1')
		file = mw.ustring.gsub(file, '|%s*right%s*([|%]])', '%1')
		file = mw.ustring.gsub(file, '|%s*center%s*([|%]])', '%1')
		file = mw.ustring.gsub(file, '|%s*framed?%s*([|%]])', '%1')
		file = mw.ustring.gsub(file, '|%s*frameless%s*([|%]])', '%1')
		file = mw.ustring.gsub(file, '|%s*upright%s*([|%]])', '%1')
		file = mw.ustring.gsub(file, '|%s*upright%s*=.-([|%]])', '%1')
		-- remove spaces prior to captions (which cause pre-formatted text)
		file = mw.ustring.gsub
		-- remove sizes, which sometimes get mistaken for captions
		file = mw.ustring.gsub(file, '|%d*x?%d+px([|%]])', '%1')
		-- expand templates
		file = mw.ustring.gsub
		-- remove loose closing braces which don't have matching opening braces
		file = mw.ustring.gsub
		-- remove loose opening braces which don't have matching closing braces 
		file = mw.ustring.gsub
		file = mw.ustring.gsub
		file = mw.ustring.gsub
		-- remove linebreaks
		file = mw.ustring.gsub
		file = mw.ustring.gsub
		-- remove surrounding square brackets
		file = mw.ustring.gsub
		file = mw.ustring.gsub
		table.insert
	end
	return files
end

function makeTranscludedGalleryLinesTables(args)
	local namespaceNumber = function(pagetitle)
		local titleObject = mw.title.new(pagetitle)
		return titleObject and titleObject.namespace
	end
	local lines = {}
	local i = 1
	while args[i] do
		if namespaceNumber(args[i]) == 6 then -- file namespace
			-- args[i] is either just the filename, or uses syntax File:Name.jpg##Caption##Credit
			local parts = mw.text.split
			local filename = parts[1]
			local caption = args['caption'..i] or args['설명'..i] or parts[2] or false
			local credit = args['credit'..i] or args['크레딧'..i] or parts[3] or false
			local line = makeGalleryLine
			table.insert
		else
			local content, pagename = excerptModule.getContent(args[i])
			if not pagename then
				return error
			elseif not content then
				return error
			end
			if args['section'..i] or args['문단'..i] then
				content = excerptModule.getsection or ''
			end
			content = excerptModule.cleanupText(content)
	
			local galleryFiles = extractGalleryFiles(content)
			if galleryFiles then
				for _, f in pairs(galleryFiles) do
					if hasCaption(f) then
						local filename = string.gsub
						local isOkay = excerptModule.checkimage(filename)
						if isOkay then
							table.insert
						end
					end
				end
			end
	
			local otherFiles = excerptModule.parse
			if otherFiles then
				for _, f in pairs(extractRegularFiles(otherFiles)) do
					if f and f ~= '' and mw.ustring.sub == 'File:' and hasCaption(f) then
						table.insert
					end
				end
			end
		
		end
		i = i + 1
	end
	return ( #lines > 0 ) and lines or error('No images found')
end

p._main = function
	if not args[1] then
		return error
	end
	local lines = transclude and makeTranscludedGalleryLinesTables(args) or makeGalleryLinesTable(args)
	return makeOutput(lines, args.width or '100%', containerClassName or 'randomSlideshow-container', isDeclined(args.random))
end

p.main = function(frame)
	local parent = frame.getParent(frame)
	local parentArgs = parent.args
	local args = cleanupArgs(parentArgs)
	local output = p._main
	return frame:extensionTag{ name='templatestyles', args = { src='무작위 슬라이드쇼/styles.css'} } 
		.. frame:preprocess(output)
end

p.transclude = function(frame)
	local parent = frame.getParent(frame)
	local parentArgs = parent.args
	local args = cleanupArgs(parentArgs)
	local output = p._main
	return frame:extensionTag{ name='templatestyles', args = { src='무작위 슬라이드쇼/styles.css'} } 
		.. frame:preprocess(output)
end