-- @brief
--  Backend for {{CATEGORYTOC}}
-- 
-- @details
--  Generates the TOC of the category according to its language.
-- 
-- @author
--  [[meta:User:Danny B.]]
local _module = {}
----------------------------------------


local Alphabet = require "Module:CATEGORYTOC/Alphabet"
local Error = require "Module:Error"


function _module.print( frame )
	
	local output = ""
	local parentFrame = frame:getParent()
	local templateArgs = parentFrame.args
	local errorData = { template = "CATEGORYTOC" }
	
	local titleObject = mw.title.getCurrentTitle()
	local lang = mw.text.trim( templateArgs["1"] or "" )
	
	local pagesInCategory = mw.site.stats.pagesInCategory( titleObject.text, "pages" )
	-- expensive++
	
	
	if pagesInCategory > 200 then
		
		if titleObject:inNamespace( "Category" ) then
			if lang == "" then
				errorData.text = "Chýba špecifikácia jazyka (1. parameter)."
				errorData.category = "Špecifikovať jazyk"
			elseif not Alphabet[lang] then
				errorData.text = "Neznámy kód jazyka „" .. lang .."“ (1. parameter)."
				errorData.category = "Skontrolovať jazyk"
			end
			if errorData.text then 
				output = output .. Error.getText( errorData )
			end
		end
		
		output = output .. "<div class=\"categorytoc toccolours\">\n"
		output = output .. "<h2>{{int:toc}}</h2>\n"
		
		if not Alphabet[lang] then
			lang = "-"
		end
		
		for index, value in ipairs( Alphabet[lang] ) do
			output = output .. "[" .. titleObject:fullUrl( { from = value } ) .. " " .. value .. "]\n"
		end
		
		output = output .. "</div>"
		
	end
	
	output = frame:preprocess( output )
	
	return output
	
end


----------------------------------------
return _module