--[=[
Implements anchor templates
]=]
require('strict')

local getArgs = require('Module:Arguments').getArgs

local function error_message(message)
	return require('Module:Error')['error']({['message'] = message})
end

local p = {}

-- [[Template:Anchor]]

function p._anchor(args)
	local anchorList = {}
	for k, v in pairs(args) do
		if v then
			anchorList[#anchorList + 1] = '<span id="' .. v .. '"></span>'
		end
	end
	return table.concat(anchorList)
end

function p.anchor(frame)
	return p._anchor(getArgs(frame))
end

-- [[Template:Anchor link]]

function p._anchor_link(args)
	local anchor = mw.uri.anchorEncode(args.anchor or args[1])
	local pageno = args.pageno or args[2]
	local subpage = args.subpage or args[3]
	
	local page = mw.title.getCurrentTitle()
	
	if not anchor then
		return error_message('No anchor specified')
	end
	if page.nsText == 'Page' and not pageno then
		return error_message('No page number specified')
	end
	
	local title = page.text
	if page.nsText == 'Page' then
		title = page.rootText .. '/' .. pageno
	elseif subpage then
		local rootSubpageTitle = mw.title.makeTitle(page.nsText, page.rootText .. '/' .. subpage)
		local baseSubpageTitle = mw.title.makeTitle(page.nsText, page.baseText .. '/' .. subpage)
		if rootSubpageTitle.exists then
			title = rootSubpageTitle.text
		elseif baseSubpageTitle.exists then
			title = baseSubpageTitle.text
		end
	end
	
	return '[[' .. mw.title.makeTitle(page.nsText, title, anchor).fullText .. '|' .. anchor .. ']]'
end

function p.anchor_link(frame)
	return p._anchor_link(getArgs(frame))
end

-- [[Template:Anchor link 2]]

function p._anchor_link_2(args)
	local subpage = args.subpage or args[1]
	local pageno = args.pageno or args[2]
	local anchor = mw.uri.anchorEncode(args.anchor or args[3])
	local text = args.text or args[4] or anchor
	
	local page = mw.title.getCurrentTitle()
	
	if not anchor then
		return error_message('No anchor specified')
	end
	if page.nsText == 'Page' and not pageno then
		return error_message('No page number specified')
	end
	
	local title = page.text
	if page.nsText == 'Page' then
		title = page.rootText .. '/' .. pageno
	elseif subpage then
		local rootSubpageTitle = mw.title.makeTitle(page.nsText, page.rootText .. '/' .. subpage)
		local baseSubpageTitle = mw.title.makeTitle(page.nsText, page.baseText .. '/' .. subpage)
		local baseSubpageBaseTitle = mw.title.makeTitle(page.nsText, baseSubpageTitle.baseText .. '/' .. subpage)
		local subpageTitle = mw.title.makeTitle(page.nsText, subpage)
		if rootSubpageTitle.exists then
			title = rootSubpageTitle.text
		elseif baseSubpageTitle.exists then
			title = baseSubpageTitle.text
		elseif baseSubpageBaseTitle.exists then
			title = baseSubpageBaseTitle.text
		elseif subpageTitle.exists then
			title = subpage
		end
	end
	return '[[' .. mw.title.makeTitle(page.nsText, title, anchor).fullText .. '|' .. text .. ']]'
end

function p.anchor_link_2(frame)
	return p._anchor_link_2(getArgs(frame))
end

return p