모듈:Television ratings graph/연습장

-- This module implements .
local contrast_ratio = require('Module:Color contrast')._ratio
local aliases = {
'제목' = 'title',
'시즌제목' = 'season_title',
'그래프숨김' = 'no_graph',
'표숨김' = 'no_table',
'각주' = 'refs',
'너비' = 'width',
'높이' = 'height',
'평균' = 'average',
'국가' = 'country'
}
local function convert_number_key(k)
local num_color = string.match(k, "색(%d+)")
local num_legend = string.match(k, "범례(%d+)")
if num_color then
return "color" .. num_color
elseif num_legend then
return "legend" .. num_legend
end
return aliasesk or k
end
local function local_args(args)
local result = {}
for k, v in pairs(args) do
local new_key = aliasesk or convert_number_key(k) or k
resultnew_key = v
end
return result
end
--------------------------------------------------------------------------------
-- TVRG class
-- The main class.
--------------------------------------------------------------------------------
local TVRG = {}
-- Allow usages of  cells
function TVRG.NACell(frame,text)
	local cell = mw.html.create('td')
	local attrMatch = '(%a-*)="(^"*)"'
	
	infoParam = frame:expandTemplate{title='빈칸',args={text}}
	
	-- Gather styles of  and assign to node variable
	while true do
		local a,b = string.match(infoParam,attrMatch)
		if a == nil or b == nil then break end
		cell:attr(a,b)
		infoParam = string.gsub(infoParam,attrMatch,,1)
	end
	infoParam = string.gsub(infoParam,'%s*|%s*',,1)
	cell:wikitext(infoParam)
	
	return cell
end
-- Create the graph and table
function TVRG.new(frame,args)
	args = args or {}
	local categories = 
	local title = mw.title.getCurrentTitle()
	
	-- Variables
	local timeline = 
	local longestseason = -1
	local average = args.average and 1 or 0
	local season_title = args.season_title or '시즌'
	local root = mw.html.create('div')
		:attr('align', 'center')
	
	-- Create the timeline
	
	-- Number of actual viewer numbers
	local numberargs = 0
	for k,v in pairs(args) do 
		if (string.lower(v) == 'n/a') or (string.lower(v) == '없음') or (not string.match(k,'^%d+') and not string.match(v,'^%d%.+')) then numberargs = numberargs + 1 end
	end
	-- Determine number of seasons
	local num_seasons = -1
	for k,v in pairs(args) do
		local thisseason = tonumber(string.sub(k,6))
		if string.sub(k,1,5) == 'color' and thisseason > num_seasons then
			num_seasons = thisseason
		end
	end
	if num_seasons = 80 then barwidth = 9
	elseif num_episodes >= 50 then barwidth = 10
	elseif num_episodes >= 20 then barwidth = 11
	else barwidth = 12
	end
	local graphwidth = num_episodes*barwidth
	
	-- Determine maximum viewer figure
	local maxviewers = -1
	local multiple = '100만'
	for k,v in pairs(args) do
		local num = tonumber(v)
		if tonumber(k) ~= nil and num ~= nil and num > maxviewers then
			maxviewers = num
		end
	end
	if maxviewers  longestseason then
				longestseason = thisseason
			end
			thisseason = 0
		elseif average == 0 or (average == 1 and argsk+1 ~= '-' and argsk+1 ~= nil) then
			-- Include bar for viewer figure, do not include if averages are included and the next parameter is a new season marker
			timeline = timeline .. "\n bar:"..bar.." from:0 till:"..(v ~=  and v or 0).." color:season"..season.."\n"
			
			-- Increment tracking variables
			counted_episodes = counted_episodes + 1
			thisseason = thisseason + 1
			bar = bar + 1
		end
	end
	-- Determine highest number of episodes in a season after final season's bars
	if thisseason > longestseason then
		longestseason = thisseason
	end
	
	-- Axis labels
	local countryDisplayUS, countryDisplayUK, countryDisplayOther
	if args.country ~= nil and args.country ~=  then
		if args.country == "U.S." or args.country == "미국" or args.country == "US" or args.country == "United States" then countryDisplayUS = "미국"
		elseif args.country == "U.K." or args.country == "영국" or args.country == "UK" or args.country == "United Kingdom" then countryDisplayUK = "영국"
		else countryDisplayOther = args.country end
	end
	
	-- If there's a title, add it with the viewers caption, else just display the viewers caption by itself
	if args.title ~= nil and args.title ~=  then
		root:wikitext("" .. args.title .. "" .. " " .. ": " .. ((countryDisplayUS or countryDisplayUK or countryDisplayOther) or "") .. ((countryDisplayUS or countryDisplayUK or countryDisplayOther) and " " or "") .. "에피소드별 시청자 수(" .. multiple .. ")"):css('margin-top', '1em')	else
		root:wikitext("에피소드별 시청자 수 (" .. multiple .. ")"):css('margin-top', '1em')
	end
	root:tag('div'):css('clear','both')
	
	-- Add timeline to div
	if args.no_graph == nil then
		if num_episodes > 100 then
			root:tag('div'):wikitext("너무 많은 그래프를 사용했습니다(최대 100개).")
			if title.namespace == 0 then
				categories = categories .. '분류:그래프에 너무 많은 수치를 입력한 틀:텔레비전 시청률 그래프를 사용한 문서'
			end
		else
			timelineBase = frame:preprocess(""..timeline.."")
			root:node(timelineBase)
			root:tag('div'):css('clear','both')
		end
	end
	
	-- Create ratings table
	if args.no_table == nil then
		local rtable = mw.html.create('table')
		   	:addClass('wikitable')
			:css('text-align', 'center')
		
			-- Create headers rows
			local row = rtable:tag('tr')
			row:tag('th'):wikitext(season_title)
				:attr('scope','col')
				:attr('colspan','2')
				:attr('rowspan','2')
				:css('padding-left', '.8em')
				:css('padding-right', '.8em')
				
			row:tag('th')
				:attr('scope','colgroup')
				:attr('colspan',longestseason)
				:wikitext("에피소드 번호")
				:css('padding-left', '.8em')
				:css('padding-right', '.8em')
				
			-- Average column
			if average == 1 then
				row:tag('th')
				   :attr('scope','col')
				   :attr('rowspan','2')
				   :wikitext("평균")
				   :css('padding-left', '.8em')
				   :css('padding-right', '.8em')
			end
			local row = rtable:tag('tr')
			
			for i = 1,longestseason do
				row:tag('th')
				   :attr('scope','col')
				   :wikitext(i)
			end
		
		local season = 1
		local thisseason = 0
		
		-- Create table rows and cells
		for k,v in pairs(args) do
			if tonumber(k) ~= nil then
				-- New season marker, or final episode rating
				if v == '-'  or (average == 1 and argsk+1 == nil) then
					if season > 1 then
						-- Spanning empty cells with 
						if thisseason 시청자 측정 수행 기관: 닐슨 미디어 리서치" .. (args.refs ~=  and args.refs or tostring(span)))
	elseif countryDisplayUK then
		root:wikitext("시청자 측정 수행 기관: 방송사 시청자 조사 위원회" .. (args.refs ~=  and args.refs or tostring(span)))
	else
		root:wikitext("출처: " .. (args.refs ~=  and args.refs or tostring(span)))
	end
	
	return tostring(root) .. categories
end
--------------------------------------------------------------------------------
-- Exports
--------------------------------------------------------------------------------
local p = {}
function p.main(frame)
local args = require('Module:Arguments').getArgs(frame, {
removeBlanks = false,
wrappers = '틀:텔레비전 시청률 그래프/연습장'
})
args = local_args(args)
return TVRG.new(frame,args)
end
return p