local p = {}
local defaultDocPage = 'doc'

local getType = function( namespace, page )
	local pageType = 'template'
	if namespace == 'Module' then
		pageType = 'module'
	elseif namespace == 'Widget' then
		pageType = 'widget'
	elseif page.fullText:gsub( '/' .. defaultDocPage .. '$', '' ):find( '%.css$' ) then
		pageType = 'stylesheet'
	elseif page.fullText:gsub( '/' .. defaultDocPage .. '$', '' ):find( '%.js$' ) then
		pageType = 'script'
	elseif namespace == 'MediaWiki' then
		pageType = 'message'
	end
	
	return pageType
end

-- Creating a documentation page or transclusion through {{subst:docc}}
function p.create( f )
	local args = require( 'Module:ProcessArgs' ).norm()
	local page = mw.title.getCurrentTitle()
	local docPage = args.page or page.nsText .. ':' .. page.baseText .. '/' .. defaultDocPage
	
	local out
	if not args.content and tostring( page ) == docPage then
		out = f:preprocess( '{{subst:Template:Documentation/preload}}' )
	else
		local templateArgs = {}
		for _, key in ipairs{ 'type', 'page', 'content' } do
			local val = args[key]
			if val then
				if key == 'content' then val = '\n' .. val .. '\n' end
				table.insert( templateArgs, key .. '=' .. val )
			end
		end
		
		out = '{{documentation|' .. table.concat( templateArgs, '|' ) .. '}}'
		out = out:gsub( '|}}', '}}' )
		
		if not args.content then
			out = out .. '\n<!-- Put categories/interwikis on the documentation page -->'
		end
	end
	
	if not mw.isSubsting() then
		out = f:preprocess( out )
		if not args.nocat then
			out = out .. '[[Category:Pages with templates requiring substitution]]'
		end
	end
	
	return out
end

-- Header on the documentation page
function p.docPage( f )
	local args = require( 'Module:ProcessArgs' ).merge( true )
	local badDoc = args.baddoc
	if f:callParserFunction( '#dplvar', '$doc noheader' ) == '1' then
		if badDoc then
			f:callParserFunction( '#dplvar:set', '$doc bad', '1' )
		end
		return
	end
	
	local page = mw.title.getCurrentTitle()
	local subpage = page.subpageText
	if subpage == 'sandbox' or subpage == 'testcases' then
		page = page.basePageTitle
	end
	local namespace = page.nsText
	local pageType = mw.ustring.lower( args.type or getType( namespace, page ) )
	
	local body = mw.html.create( 'div' ):addClass( 'documentation-header' )
	body
		:addClass( badDoc and 'documentation-badDoc' or '' )
		:tag( 'div' )
			:attr( 'id', 'documentation-header-tools' )
			:wikitext( '[[', page:fullUrl( 'action=purge' ), ' ' .. f:preprocess('{{lc:{{int:smw purge}}}}') .. ']]' )
		:done()
		:wikitext(
			'This is the documentation page. It ',
			pageType == 'module' and 'will' or 'should',
			' be transcluded into the main ', pageType, ' page. ',
			'See [[Template:Documentation]] for more information'
		)
	if badDoc then
		body:wikitext( "<br>'''This ", pageType, "'s documentation needs improving or additional information.'''" )
	end
	if not ( args.nocat or namespace == 'User' ) then
		body:wikitext( '[[Category:Documentation pages]]' )
	end
	
	return body
end

-- Wrapper around the documentation on the main page
function p.page( f )
	-- mw.text.trim uses mw.ustring.gsub, which silently fails on large strings
	local function trim( s )
		return (s:gsub( '^[\t\r\n\f ]+', '' ):gsub( '[\t\r\n\f ]+$', '' ))
		--return string.gsub( s, '^[\t\r\n\f ]*(.-)[\t\r\n\f ]*$', '%1' )
	end
	local args = require( 'Module:ProcessArgs' ).merge( true )
	local page = mw.title.getCurrentTitle()
	local subpage = page.subpageText
	if subpage == 'sandbox' or subpage == 'testcases' then
		page = page.basePageTitle
	end
	local namespace = page.nsText
	local docText = trim( args.content or '' )
	if docText == '' then docText = nil end
	
	local docPage
	local noDoc
	if docText then
		docPage = page
	else
		docPage = mw.title.new( args.page or namespace .. ':' .. page.text .. '/' .. defaultDocPage )
		noDoc = args.nodoc or not docPage.exists
	end
	local badDoc = args.baddoc
	local pageType = mw.ustring.lower( args.type or getType( namespace, page ) )
	
	if not docText and not noDoc then
		f:callParserFunction( '#dplvar:set', '$doc noheader', '1' )
		docText = trim( f:expandTemplate{ title = ':' .. docPage.fullText }  )
		if f:callParserFunction( '#dplvar', '$doc bad' ) == '1' then
			badDoc = 1
		end
		
		if docText == '' then
			docText = nil
			noDoc = 1
		end
	end
	if docText then
		docText = '\n' .. docText .. '\n'
	end
	
	local docClass = ''
	local message
	local category
	if noDoc then
		docClass = 'documentation-noDoc'
		message = "'''This " .. pageType .. " has no documentation. " ..
			"If you know how to use this " .. pageType .. ", please create it.'''"
		if not ( args.nocat or namespace == 'User' ) then
			category = pageType .. 's with no documentation'
			if not mw.title.new( 'Category:' .. category ).exists then
				category = 'Pages with no documentation'
			end
		end
	elseif badDoc then
		docClass = 'documentation-badDoc'
		message = "'''This " .. pageType .. "'s documentation needs improving or additional information.'''\n"
		if not ( args.nocat or namespace == 'User' ) then
			category = pageType .. 's with bad documentation'
			if not mw.title.new( 'Category:' .. category ).exists then
				category = 'Pages with bad documentation'
			end
		end
	end
	
	-- Generates the [view][edit][history][refresh] or [create][refresh] links
	local links = mw.html.create( 'span' )
		:attr( 'id', 'documentation-header-tools' )

	local purgeLink = '[[Special:Purge/' .. docPage.fullText .. '|' .. f:preprocess('{{lc:{{int:smw purge}}}}') .. ']]'
	if not noDoc and page ~= docPage then
		local viewLink = '[[' .. docPage.fullText .. '|' .. f:preprocess('{{lc:{{int:view}}}}') .. ']]'
		local editLink = '[[Special:EditPage/' .. docPage.fullText .. '|' .. f:preprocess('{{lc:{{int:edit}}}}') .. ']]'
		local historyLink = '[[Special:PageHistory/' .. docPage.fullText .. '|' .. f:preprocess('{{lc:{{int:history short}}}}') .. ']]'
		links:wikitext("&#91;" .. viewLink .. "&#93; &#91;" .. editLink .. "&#93; &#91;" .. historyLink .. "&#93; &#91;" .. purgeLink .. "&#93;")
	else
		local createLink = '[' .. docPage:canonicalUrl{action = 'edit', preload = 'Template:Documentation/preload' } .. ' ' .. f:preprocess('{{lc:{{int:create}}}}') .. ']'
		links:wikitext("&#91;" .. createLink .. "&#93; &#91;" .. purgeLink .. "&#93;")
	end
	
	local body = mw.html.create( 'div' ):addClass( 'documentation' )
	body
		:addClass( docClass )
	
	local header = mw.html.create( 'div' )
		:addClass( 'documentation-header-top' )
	
	header
		:node( links )
		:tag( 'span' )
			:addClass('documentation-header-title' )
			:wikitext( 'Documentation' )
	
	local codePages = {
		module = true,
		stylesheet = true,
		script = true,
	}
	if not noDoc and codePages[pageType] then
		header
			:tag( 'span' )
				:attr( 'id', 'documentation-jump-to-code' )
				:wikitext( '[[#the-code|Jump to code ↴]]' )
	end
	
	body
		:node( header ):done()
		:wikitext( message )
		:wikitext( docText )
	
	if not noDoc and page ~= docPage then
		body
			:tag( 'div' )
				:addClass( 'documentation-header-bottom' )
				:node( links )
				:wikitext( 'The above documentation is transcluded from [[', docPage.fullText, ']].' )
	end
	
	local anchor = ''
	if not noDoc and pageType ~= 'template' and pageType ~= 'message' then
		anchor = mw.html.create( 'div' ):attr( 'id', 'the-code' )
	end
	
	return mw.getCurrentFrame():extensionTag('templatestyles', '', {src='Module:Documentation/styles.css'}) .. tostring( body ) .. tostring( anchor )
end

return p