local p = {}
local lib = require('Module:Feature')
local getTemplateArgs = require('Module:Parser').getTemplateArgs

-- [[Template:Tutorial]]
function p.Tutorial(frame, args)
	if args == nil then
		args = require('Module:Arguments').getArgs(frame, { parentFirst = true })
	end
	
	if args[1] and type(args[1]) == 'string' then
		local tutorialArgs = getTemplateArgs('Tutorial/' .. args[1], { only = 'Tutorial' })
		if lib.isEmpty(tutorialArgs) then
			return mw.html.create('strong'):addClass('error'):wikitext('The page [[Tutorial/', args[1], ']] is not a valid tutorial.')
		else
			local html = mw.html.create():tag('div'):addClass('tutorial')
			html:tag('dl'):tag('dt'):wikitext(tutorialArgs.title or args[1])
			p._TutorialFormat(tutorialArgs, html)
			return frame:preprocess(tostring(html))
		end
	else
		local html = mw.html.create():tag('div'):addClass('tutorial')
		p._TutorialFormat(args, html)
		return html
	end
end

function p._TutorialFormat(args, out)
	local title = mw.title.getCurrentTitle()
	if args.about then
		args.about = lib.split(args.about, ';')
		if title.rootText == 'Tutorial' then
			-- out:tag('i'):wikitext(require('Module:Hatnote').main(args.about))
			-- out:tag('i'):wikitext(mw.getCurrentFrame():expandTemplate{ title = 'main', args = args.about })
			out:tag('i'):wikitext(require('Module:Labelled list hatnote')._labelledList(
				args.about,
				{ "Main article", "Main articles", "Main page", "Main pages" },
				{}
			))
		end
	end
	
	local size = args.size or '200px'
	if (title.rootText == 'Tutorial') then
		size = '400px'
	end
	
	--create format
	local I = 1
	while (args['image' .. tostring(I)] or args['text' .. tostring(I)]) do
		local image = args['image' .. tostring(I)]
		local text = args['text' .. tostring(I)]
		if (image or text) then
			local row = out:tag('div')
			row:wikitext('[[File:', (image or 'Empty.png'), '|', size, ']]')
			row:tag('span'):addClass('hidden'):wikitext((text or '<wbr>'))
			if text then
				row:tag('span'):addClass('mobile-only'):wikitext('<br />', text)
				if (args['image' .. tostring(I+1)] or args['text' .. tostring(I+1)]) then
					row:tag('hr'):addClass('mobile-only')
				end
			end
		end
		I = I + 1
	end
	
	--categories if correct page
	local subpage = args.title or title.subpageText
	if (not args['table'] and title.baseText == 'Tutorial' and (subpage ~= nil and not lib.inArray({'Elements', 'Enemies', 'System', 'Adventure', 'Uncategorized'}, subpage))) then
		local cat = mw.html.create()
		cat:wikitext('[[Category:Tutorials|', subpage, ']]')
		if args['sort'] then
			cat:wikitext('[[Category:Tutorial|', string.format('%05d', args['sort']), ']]')
		else
			cat:wikitext('[[Category:Tutorial]]')
		end
		
		-- Code for Tutorial groups - we don't have these yet
		-- In the array: list of valid group types
		if lib.inArray({}, args['type']) then
			cat:wikitext('[[Category:', args['type'], ' Tutorials|', subpage, ']]')
			if not args['sort'] then
				cat:wikitext('[[Category:Tutorial Missing Sort]]')
			end
		else
			cat:wikitext('[[Category:Uncategorized Tutorials|', subpage, ']]')
		end
		if args.about then
			for _, v in pairs(args.about) do
				cat:wikitext('[[Category:', v, ' Tutorials]]')
			end
		end
		if not args.nocat then
			out:node(require('Module:Namespace detect')._main{main=cat, module=cat})
		end
	end
end

-- [[Template:Tutorials by Category Table]]
function p.Table(frame)
	local args = require('Module:Arguments').getArgs(frame, { parentFirst = true })
	local result = mw.html.create('div'):addClass('tutorial-table')
	local title = mw.title.getCurrentTitle().text
	
	if lib.isEmpty(args.pages) then
		result:tag('span'):wikitext('No [[Tutorial]]s ', (args[1] and 'that match the category selection' or 'are in ' .. title), '.')
	else
		local resultTable = mw.html.create('table'):addClass('article-table')
		local count = 0
		for tutorialPage in lib.gsplit(args.pages, ';;;', { noTrim = true, removeEmpty = true }) do
			local tutorialArgs = getTemplateArgs(tutorialPage, { only = 'Tutorial' })
			for key, value in pairs(tutorialArgs) do
				if value == '' then tutorialArgs[key] = nil end	
			end
			resultTable:node(p._TableRow(tutorialArgs))
			count = count + 1
		end
		
		local header = result:tag('div'):addClass('tutorial-header')
		if lib.isNotEmpty(args.header) then
			header:wikitext(tostring(tostring(args.header):gsub('%%PAGES%%', count)))
		else
			header:wikitext(
				'There ',
				(count == 1 and 'is ' or 'are '),
				"'''",
				count,
				"'''",
				' [[Tutorial]]',
				(count == 1 and ' ' or 's '),
				(args[1] and ('that match' .. (count == 1 and 'es' or '') .. ' the category selection:') or ' are in ' .. title)
			)
		end
		result:node(resultTable)
	end
	
	return frame:preprocess(tostring(result))
end

function p._TableRow(args)
	local out = mw.html.create('')
	
	if args.title then
		local header = out:tag('tr'):tag('th')
		header:wikitext('[[Tutorial/', args.title, '|', args.title, ']]')
		if args.subtitle then
			header:wikitext(' - ', args.subtitle)
		end
		if args.icon then
			header:wikitext(' [[File:', args.icon, '|25px|link=]]')
		end
		
		local row = out:tag('tr'):tag('td')
		args['table'] = true
		row:node(p.Tutorial(frame, args))
	end
	return out
end

return p