모듈:Football box

-- Implements [[틀:축구 경기 정보]]
local p = {}
local lang = nil
local delink = require('모듈:Delink')._delink
local eventschema = "http://schema.org/SportsEvent"
local teamschema = "http://schema.org/SportsTeam"
local placeschema = "http://schema.org/Place"
local penalties = '[[승부차기]]'
local aet = '[[연장전#축구|연장전]]'
local asdet = '[[서든 데스|서든 데스 연장전]]'
local agget = '[[연장전#축구|연장전]]/[[골든골]]'
local asget = '[[연장전#축구|연장전]]/[[실버골]]'
local attendance = '관중:'
local referee = '심판:'
local templatestyles = '모듈:Football box/styles.css'

local tracking, preview

local function checkarg(k,v)
	if not k or type(k) ~= 'string' then return end
	
	if  k == 'assistantreferees2' then
		table.insert(tracking, '[[분류:축구 경기 정보 틀에 assistantreferees 변수를 사용한 문서|2]]')
	elseif k == 'aggregatescore' or k == '합계 득점' or k == 'assistantreferees' or 
			k == 'fourthofficial' or k == 'game' or k == 'motm' or k == '맨 오브 더 매치' or 
			k == 'nobars' or k == 'note' or k == '비고' or k == 'result' or k == '결과' then
		-- valid and tracked
		table.insert(tracking, '[[변수:축구 경기 정보 틀에 ' .. k .. ' 변수를 사용한 문서]]')
			elseif k == 'size' or k == '크기' or k == 'bg' or k == '배경' or k == 'id' or k == '앵커' or 
		k == 'event' or k == '이벤트' or k == 'date' or k == '날짜' or k == 'time' or k == '시간' or 
		k == 'round' or k == '라운드' or k == 'team1' or k =='팀1' or k == 'team2' or k =='팀2' or 
		k == 'score1' or k == '득점1' or k == 'score2' or k == '득점2' or k == 'score' or k == '득점' or 
		k == 'scorenote' or k == '스코어노트' or k == 'aet' or k == '연장전' or k == 'asdet' or 
		k == '서든데스' or k == 'agget' or k == '골든골' or k == 'asget' or k == '실버골' or 
		k == 'goals1' or k == '골1' or k == 'report' or k == '리포트' or k == 'goals2' or k == '골2' or 
		k == 'penaltyscore' or k == '승부차기득점' or 
		k == 'penalties1' or k == '승부차기1' or k == 'penalties2' or k == '승부차기2' or 
		k == 'stadium'  or k == '경기장' or k == 'location' or k == '도시' or 
		k == 'attendance' or k == '관중수' or k == 'referee' or k == '심판' or k == 'stack' or 
		k == 'section' or k == 'transcludesection' then
		-- valid and not tracked
	else
		-- invalid
		local vlen = mw.ustring.len(k)
		k = mw.ustring.sub(k, 1, (vlen < 25) and vlen or 25) 
		k = mw.ustring.gsub(k, '[^%w%-_ ]', '?')
		table.insert(tracking, '[[분류:축구 경기 정보 틀에 알 수 없는 변수를 사용한 문서|' .. k .. ']]')
		table.insert(preview, '"' .. k .. '"')
	end
end

local function timestamp(d, t)
	if not d then return nil end
	
	lang = lang or mw.language.getContentLanguage() -- lazy initialize
	local success, timestamp = pcall(lang.formatDate, lang, 'c', delink({d .. ' ' .. (t or '')}))
	if success then
		return timestamp
	else
		return nil
	end
end

local function fmtlist(s)
	s = mw.ustring.gsub(s or '', '%[%[ *([%?-]) *%]%]', '%1')
	s = mw.ustring.gsub(s, '%[%[ *[%?-] *| *(.-) *%]%]', '%1')
	if mw.ustring.sub(s, 1, 1) == '*' then
		-- could also expand plainlist here
		return mw.getCurrentFrame():extensionTag{
			name = 'templatestyles', args = { src = 'Plainlist/styles.css' }
		} .. tostring(  mw.html.create('div'):addClass('plainlist'):newline():wikitext(s))
	end
	return s
end

local function makelink(s,t)
	if s:match('^[Hh][Tt][Tt][Pp][Ss]?:[^ ]*$') then
		return '[' .. s .. ' ' .. t .. ']'
	end
	return s
end

local function trim(s)
	return s:match('^[\'"%s]*(.-)[\'"%s]*$')
end

local function getid(s)
	s = trim(s or '')
	if s and s ~= '' then
		return s
	end
	return nil
end

local function makeanchor(s)
	s = mw.ustring.gsub(s, '%[%[[Ff][Ii][Ll][Ee]:[^%[%]]*%]%]', '')
	s = mw.ustring.gsub(s, '<[Ss][Pp][Aa][Nn][^<>]*>', '')
	s = mw.ustring.gsub(s, '</[Ss][Pp][Aa][Nn][^<>]*>', '')
	s = mw.ustring.gsub(s, '[\'"]', '')
	s = mw.ustring.gsub(s, '%s*&nbsp;%s*', ' ')
	s = mw.ustring.gsub(s, '%[%[[^%[%]%|]*%|([^%[%]]*)%]%]', '%1')
	s = mw.ustring.gsub(s, '%[%[([^%[%]]*)%]%]', '%1')
	s = mw.ustring.gsub(s, '\127[^\127]*UNIQ%-%-[^\127]*%-%x+%-QINU[^\127]*\127', '')
	s = mw.ustring.gsub(s, '<[Ss][Uu][Pp]>[^<>]*</[Ss][Uu][Pp]>', '')
	s = mw.ustring.gsub(s, '%s%s*', ' ')
	return s
end

local function checkTitle()
    local pageTitle = mw.title.getCurrentTitle().text
    local titlePhrases = {
        "group stage", "knockout stage", "knockout phase", "final phase", "league phase",
        "round", "league stage", "qualifying", "qualification", "play-?off", "nations league [a-d]", "intertoto"
    }
    
    for _, phrase in ipairs(titlePhrases) do
        if mw.ustring.match(mw.ustring.lower(pageTitle), phrase) then
            return true
        end
    end
    
    return false
end

function p.main(frame)
	-- Exit early if we are using section transclusion for a different section
	local tsection = frame:getParent().args['transcludesection'] or frame:getParent().args['section'] or ''
	local bsection = frame.args['section'] or ''
	if( tsection ~= '' and bsection ~= '' ) then
		if( tsection ~= bsection ) then
			return ''
		end
	end

	local args = require('모듈:Arguments').getArgs(frame)

		args['aggregatescore'] = args['합계 득점'] or args['aggregatescore']
		args['motm'] = args['맨 오브 더 매치'] or args['motm']
		args['note'] = args['비고'] or args['note']
		args['result'] = args['결과'] or args['result']
		args['size'] = args['크기'] or args['size']
		args['bg'] = args['배경'] or args['bg']
		args['event'] = args['이벤트'] or args['event']
		args['date'] = args['날짜'] or args['date']
		args['time'] = args['시간'] or args['time']
		args['round'] = args['라운드'] or args['round']
		args['team1'] = args['팀1'] or args['team1']
		args['team2'] = args['팀2'] or args['team2']
		args['score1'] = args['득점1'] or args['score1']
		args['score2'] = args['득점2'] or args['score2']
		args['score'] = args['득점'] or args['score']
		args['scorenote'] = args['스코어노트'] or args['scorenote']
		args['aet'] = args['연장전'] or args['aet']
		args['asdet'] = args['서든데스'] or args['asdet']
		args['agget'] = args['골든골'] or args['agget']
		args['asget'] = args['실버골'] or args['asget']
		args['goals1'] = args['골1'] or args['goals1']
		args['report'] = args['리포트'] or args['report']
		args['goals2'] = args['골2'] or args['goals2']
		args['penaltyscore'] = args['승부차기득점'] or args['penaltyscore']
		args['penalties1'] = args['승부차기1'] or args['penalties1']
		args['penalties2'] = args['승부차기2'] or args['penalties2']
		args['stadium'] = args['경기장'] or args['stadium']
		args['location'] = args['도시'] or args['location']
		args['attendance'] = args['관중수'] or args['attendance']
		args['referee'] = args['심판'] or args['referee']

	local id = getid(args['앵커'] or args['id'])
	local d = timestamp(args['date'], args['time'])
	local block

	tracking, preview = {}, {}
    for k, v in pairs(args) do
    	if v ~= '' then
    		checkarg(k,v)
    	end
	end

	local score = 'v'
	if args['score1'] or args['score2'] then
		score = (args['score1'] or '0') .. '&ndash;' .. (args['score2'] or '0')
	elseif args['score'] and args['score'] ~= '' then
		score = args['score']
	end
	if args['aet'] then
		score = score .. ' (' .. aet .. ')'
	elseif args['asdet'] then
		score = score .. ' (' .. asdet .. ')'
	elseif args['agget'] then
		score = score .. ' (' .. agget .. ')'
	elseif args['asget'] then
		score = score .. ' (' .. asget .. ')'
	end
	if args['scorenote'] then
		score = score .. '<br>' .. args['scorenote']
	end
	
	-- Generate an anchor
	if id and id == 'event' and args['event'] then
		id = makeanchor(args['event'])
	end
	if (id and id == 'auto') or (not id and checkTitle()) then
		id = makeanchor((args['team1'] or '팀 1') .. ' v ' .. (args['team2'] or '팀 2'))
	end
	
	-- Start box
	local root = 
		mw.html.create('div')
			:attr('itemscope', '')
			:attr('itemtype', eventschema)
			:addClass('footballbox')
			:css('width', args['size'])
			:css('background-color', args['bg'])
			:attr('id', id)
	root:newline()
	
	if args['event'] then
		root:tag('div')
			:addClass('ftitle')
			:wikitext(args['event'])
	end
	
	-- Start left block
	block = root:tag('div')
		:addClass('fleft')
	
	local timetag = block:tag('time')
		:attr('itemprop', d and 'startDate' or nil)
		:attr('datetime', d)
		
	timetag:tag('div')
		:addClass('fdate')
		:wikitext(args['date'])
	
	if args['time'] then
		timetag:tag('div')
			:addClass('ftime')
			:wikitext(args['time'])
	end
	
	if args['round'] then
		block:tag('div')
			:addClass('frnd')
			:wikitext(args['round'])
	end
	-- End block
	
	-- Start table
	local rtable = root:tag('table')
		:addClass('fevent')
	local row = rtable:tag('tr')
		:attr('itemprop', 'name')
	row:newline()
	row:tag('th')
		:addClass('fhome')
		:attr('itemprop', 'homeTeam')
		:attr('itemscope', '')
		:attr('itemtype', teamschema)
		:tag('span')
			:attr('itemprop', 'name')
			:wikitext(args['team1'])
	row:tag('th')
		:addClass('fscore')
		:wikitext(score)
	row:tag('th')
		:addClass('faway')
		:attr('itemprop', 'awayTeam')
		:attr('itemscope', '')
		:attr('itemtype', teamschema)
		:tag('span')
			:attr('itemprop', 'name')
			:wikitext(args['team2'])

	row = rtable:tag('tr')
		:addClass('fgoals')
		:newline()
	row:tag('td')
		:addClass('fhgoal')
		:wikitext(fmtlist(args['goals1']))
	row:newline()
	row:tag('td')
		:wikitext(makelink(args['report'] or '', '리포트'))
	row:newline()
	row:tag('td')
		:addClass('fagoal')
		:wikitext(fmtlist(args['goals2']))
	row:newline()	
	
	if args['penaltyscore'] then
		rtable
			:tag('tr')
				:tag('th')
					:attr('colspan', 3)
					:wikitext(penalties)
		row = rtable:tag('tr')
			:addClass('fgoals')
		row:newline()
		row:tag('td')
			:addClass('fhgoal')
			:wikitext(fmtlist(args['penalties1']))
		row:newline()
		row:tag('th')
			:wikitext(args['penaltyscore'])
		row:newline()
		row:tag('td')
			:addClass('fagoal')
			:wikitext(fmtlist(args['penalties2']))
		row:newline()
	end
	-- End table
	
	-- Start right block
	block = root:tag('div')
		:addClass('fright')
	
	if args['stadium'] then
		local sdiv = block:tag('div')
			:attr('itemprop', 'location')
			:attr('itemscope', '')
			:attr('itemtype', placeschema)
		if args['location'] then
			sdiv:tag('span')
				:attr('itemprop', 'name')
				:wikitext(args['stadium'])
			sdiv:wikitext(', ')
			sdiv:tag('span')
				:attr('itemprop', 'address')
				:wikitext(args['location'])
		else
			sdiv:tag('span')
				:attr('itemprop', 'name address')
				:wikitext(args['stadium'])
		end
	end
	
	if args['attendance'] then
		block:tag('div'):wikitext(attendance ..' ' .. args['attendance'])
	end
	if args['referee'] then
		block:tag('div'):wikitext(referee .. ' ' .. args['referee'])
	end

	local trackstr = (#tracking > 0) and table.concat(tracking, '') or ''
	if #preview > 0 then
		trackstr = require('모듈:If preview')._warning({
			'Unknown parameters ' .. table.concat(preview, '; ') .. '.'
		}) .. trackstr
	end
	
	return frame:extensionTag{ name = 'templatestyles', args = { src = templatestyles} } .. tostring(root) .. trackstr
end

return p