require('Modulo:No globals')

local wikidata = require('Modulo:Wikidata')
local navbox = require('Modulo:Navbox')
local mNumeroRomano = require('Modulo:Numero romano')
local getArgs = require('Modulo:Arguments').getArgs
local errorCategory = '[[Categoria:Errori di compilazione del template Stagioni televisive]]'
local p = {}

local function ordinalefemminile(num)
	return mw.getCurrentFrame():expandTemplate {
		title = 'Ordinale femminile',
		args = { num }
	}
end

function p.prova(frame)
	local args = getArgs(frame)
	return p._prova(args)
end

function p._prova(args)
	local template, sfondo, categoria, target, stagioneoedizione, preposizione, links, errore
	local id, localID, localID2, tipo, titolo, etichetta, nome, sitelink, stagioni
	local pageTitle = args[1] or args.titolo

-- Rileva l'identificativo della scheda wikidata collegata alla fiction o al programma TV,
-- se nessun titolo è specificato prova a recuperlo dalla voce della stagione/edizione, se questa ha una sua scheda su wikidata	
	if not args[1] or args.titolo then
		if string.find(mw.title.getCurrentTitle().text, '^Episodi d[ei]') then
		localID = wikidata._getProperty({ 'P361', n = 1, from = mw.wikibase.getEntityIdForCurrentPage(), formatting = 'raw' })
		localID2 = wikidata._getProperty({ 'P179', n = 1, from = mw.wikibase.getEntityIdForCurrentPage(), formatting = 'raw' })
		end
			if localID ~= nil then
			id = localID
			elseif localID2 ~= nil then
			id = localID2	
			end
	else id = mw.wikibase.getEntityIdForTitle( pageTitle )
	end

-- Identifica il tipo di programma (serie televisiva, serie animata o programma TV generico)
-- ed estrae gli altri dati fondamentali da Wikidata (etichetta in italiano, numero stagioni, sitelink)
-- se uno di essi non è presente è generato un messaggio di errore
	if wikidata._instanceOf({ 'Q581714', from = id }) then tipo = 'animata'
	elseif wikidata._instanceOf({ 'Q5398426', from = id }) then tipo = 'serie TV'
	else tipo = 'programma'
	end
	if id then
	titolo = wikidata._getLink({ id })
	etichetta = wikidata._getLabel({ id, 'it'})
	sitelink = mw.wikibase.sitelink( id )
	stagioni = wikidata._getProperty({ 'P2437', n = 1, from = id, formatting = 'raw' })
	else errore = 'Template non compilato correttamente, controlla le [[Template:Stagioni televisive|istruzioni]]'
	end

if not etichetta or not sitelink or not stagioni then
	errore = 'Template non compilato correttamente, controlla le [[Template:Stagioni televisive|istruzioni]]'
else

-- Questa parte del codice genere i collegamenti alle singole edizioni/stagioni e la relativa categoria
	local tbl = {}
	local lang = mw.language.getContentLanguage()
	local sep = '&nbsp;<b>&middot;</b>&#32;'

	if tipo == 'programma' then
		if string.find(mw.title.getCurrentTitle().text, '%(programma.+edizione%)$') then
		nome = sitelink	else
		nome = etichetta
		end
	elseif tipo == 'serie TV' or tipo == 'animata' then
		if string.find(mw.title.getCurrentTitle().text, '^Episodi d[ei] .+ %(.*serie') then nome = sitelink
		elseif mw.title.new(string.format('Episodi di %s (prima stagione)', sitelink)).exists or mw.title.new(string.format('Episodi de %s (prima stagione)', sitelink)).exists then
		nome = sitelink	else
		nome = etichetta
		end
	end

	if tipo == 'programma' then
		preposizione = mw.title.new(string.format('Categoria:Edizioni de %s', nome)).exists and 'de' or 'di'
	elseif tipo == 'serie TV' or tipo == 'animata' then
		if string.find(mw.title.getCurrentTitle().text, '^Episodi d[ei]') then
		preposizione = string.find(mw.title.getCurrentTitle().text, '^Episodi de') and 'de' or 'di'
		elseif mw.title.new(string.format('Episodi de %s (prima stagione)', nome)).exists or mw.title.new(string.format('Episodi de %s', nome)).exists then
		preposizione = 'de' else
		preposizione = 'di'
		end
	end

	for i = 1, stagioni do
		local ordinaleF = ordinalefemminile(i)
		
		if tipo == 'programma' then 
		target = string.format('%s (%s edizione)', nome, ordinaleF) else
		target = string.format('Episodi %s %s (%s stagione)', preposizione, nome, ordinaleF)
		end
		if tipo == 'programma' then
		stagioneoedizione = 'edizione' else
		stagioneoedizione = 'stagione'
		end
		local label = args.formato == 'numeri romani' and mNumeroRomano.main({ i }) or
					  (args.formato == 'forma breve' and string.format('%dª', i) or
					  string.format('%s %s', lang:ucfirst(ordinaleF), stagioneoedizione))
		table.insert(tbl, string.format('[[%s|%s]]', target, label))
		
		if (target == mw.title.getCurrentTitle().text and mw.title.getCurrentTitle().namespace == 0) or args.debug then
			if stagioni == '1' or stagioni == '1±0' then
				if tipo == 'programma' then categoria = string.format('[[Categoria:Edizioni di programmi televisivi|%s]]', nome)
				elseif tipo == 'animata' then categoria = string.format('[[Categoria:Liste di episodi di serie animate|%s]]', nome)
				else categoria = string.format('[[Categoria:Liste di episodi di serie televisive|%s]]', nome)
				end
			elseif tipo == 'programma' then categoria = string.format('[[Categoria:Edizioni %s %s|%02d]]', preposizione, nome, i)
			else categoria = string.format('[[Categoria:Stagioni %s %s|%02d]]', preposizione, nome, i)
			end 
		end
	end
	links = mw.text.listToText(tbl, sep, sep) .. (categoria or '')
end

-- Infine è generato il navbox con i dati su estratti e formattati
	if tipo == 'animata' then sfondo = 'background:#ab110c;'
	elseif tipo == 'serie TV' then sfondo = 'background:#115806;'
	elseif tipo == 'programma' then sfondo = 'background:#161e8e;'
	end
	
	if not id or not etichetta or not stagioni then
		template = mw.title.getCurrentTitle().namespace == 0 and errorCategory or nil
	elseif args[2] == 'elenco' or args[3] == 'elenco' or args[4] == 'elenco' then template = links
	elseif stagioni == '1' or stagioni == '1±0' then template = categoria
	else template = navbox._navbox({
			name = 'Stagioni televisive',
			title = string.format("[[%s|<span style=\"color:white;\">''%s''</span>]]", sitelink, etichetta),
			titlestyle = sfondo,
			list1 = links
		})
	end

	return template, errore
end


return p