local p = {}

local labels = {
	['penalties'] = '승부차기',
	['shootout'] = 'Shootout',
	['pen'] = '승부차기',
	['so'] = 'SO',
	['연장전'] = '연장전',
	['종합득점'] = '합계',
	['경기장'] = '경기장:', 
	['관중수'] = '관중수:',
	['심판'] = '심판:',
	['부심'] = '부심:',
	['2부심'] = '',
	['대기심'] = 'Fourth official:',
	['후보 대기심'] = '후보 대기심:',
	['goallineassistants'] = 'Goal-line assistants:',
	['goallineassistant2'] = '',
	['motm'] = '맨 오브 더 매치:',
	['potm'] = 'Player of the Match:',
	['mvp'] = 'MVP:',
	['note'] = 'Note:',
	['seealso'] = 'See also:'
local colors = {
	["W"] = "BBF3BB",
	["L"] = "FFBBBB",
	["T"] = "D" , ["D"] = "FFFFBB",
	["V"] = "P", ["P"] = "BBBBBB"

local tracking, preview

local function checkarg
	if k and type(k) == 'string' then
		if k == 'id' or k == '팀1' or k == '팀2' or k == 'class' or 
			k == 'nobars' or k == 'size' or 
			k == 'result' or k == 'bg' or k == 'format' or k == '날짜' or k == 'scorenote' or
			k == '라운드' or k == '득점' or k == '연장전' or k == '합계 득점' or 
			k == 'penaltyscore' or k == 'location' or k == '경기장' or 
			k == '시간' or k == 'goals1' or k == 'report' or k == 'goals2' or 
			k == 'attendance' or k == 'referee' or k == 'assistantreferees' or 
			k == 'assistantreferee2' or k == 'fourthofficial' or 
			k == 'fifthofficial' or k == 'goallineassistants' or 
			k == 'goallineassistant2' or k == 'potm' or k == 'motm' or 
			k == 'mvp' or k == 'penalties1' or k == 'penalties2' or k == 'note' or 
			k == 'shootoutscore' or k == 'shootout1' or k == 'shootout2' or
			k == 'seealso' or k == 'stack' 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
			table.insert
			table.insert
		end
	end
end

local function isnotempty(s)
	return s and s:match( '^%s*(.-)%s*$' ) ~= ''
end

local function trim(s)
	if isnotempty(s) then
		s = s:match('^[\'"%s]*(.-)[\'"%s]*$')
		return isnotempty(s) and s or nil
	end
	return nil
end

local function bold(s)
	if isnotempty(s) then
		return "**" .. s .. "**"
	end
	return ""
end

local function italic(s)
	if isnotempty(s) then
		return "''" .. s .. "''"
	end
	return ""
end

local function small(s)
	if isnotempty(s) then
		return ''
	end
	return ''
end

local function nowrap(s)
	if isnotempty(s) then
		return ''
	end
	return ''
end

local function background
	local data = colors
	local res = data[r:upper]
	if res then
		res = '#' .. (data[res] or res)
	elseif isnotempty(bg) then
		res = '#' .. bg
	else
		res = 'transparent'
	end
	return res
end

local function teamname(team)
 local prefix, suffix, b = "", "", "**";

 if mw.ustring.sub ~= b and mw.ustring.sub ~= b then
 prefix = b .. '" .. b;
 else
 if mw.ustring.sub == b then
 prefix = '';
 team = mw.ustring.sub;
 else
 prefix = '";
 team = mw.ustring.sub(team,1,mw.ustring.len(team)-3);
 else
 suffix = b .. "";
 end
 end
 
 return prefix .. team .. suffix;
end

local function score
	s = nowrap(bold(s ~= '' and s or 'v'))
	if a ~= '' then
		s = s .. small(' (' .. labels['연장전'] .. ')')
	end
	if ag ~= '' then
		s = s .. '' .. small(' (' .. bold(ag) .. ' ' .. labels['agg'] .. ')')
	end
	if p ~= '' then
		s = s .. '' .. small(' (' .. bold(p) .. ' ' .. labels['pen'] .. ')')
	elseif so ~= '' then
		s = s .. '' .. small(' (' .. bold(so) .. ' ' .. labels['so'] .. ')')
	end
	return s
end
 
local function fmtlist(s)
	s = mw.ustring.gsub(s or '', '%[%[ *([%?-]) *%]%]', '%1')
	s = mw.ustring.gsub(s, '%[%[ *[%?-] *| *(.-) *%]%]', '%1')
	if mw.ustring.sub == '*' then
		return tostring(mw.html.create('div'):addClass('plainlist'):newline:wikitext(s))
	end
	return s
end

local function makelink
	if s:match('^http') then
		return '[' .. s .. ' ' .. t .. ']'
	end
	return s
end

function p.main(frame)
	local args = (frame.args['팀1'] or frame.args['팀2']) and frame.args or frame:getParent.args
	local id = trim(args['id'])
	local bars = (args['nobars'] == nil) or (args['bars'] == '')
	local class = trim(args['class'] or 'mw-collapsible mw-collapsed') or ''
	local width1 = {['1'] = '28%', ['1.1'] = '22%', ['1.2'] = '28%', ['default'] = '19%'}
	local width2 = {['1'] = '19%', ['1.1'] = '25%', ['1.2'] = '19%', ['default'] = '23%'}
	local width3 = {['1'] = '8%', ['1.1'] = '8%', ['1.2'] = '8%', ['default'] = '12%'}
	local width4 = {['1'] = '19%', ['1.1'] = '19%', ['1.2'] = '26%', ['default'] = '23%'}
	local width5 = {['1'] = '26%', ['1.1'] = '26%', ['1.2'] = '19%', ['default'] = '23%'}
	local location = nil
	local extra = {}
	local notes = {}
	
	tracking, preview = {}, {}
 for k, v in pairs(args) do
 	if v ~= '' then
 		checkarg
 	end
	end
	
	if args['class'] then
		if args['class'] == 'collapsible' or args['class'] == 'mw-collapsible' or args['class'] == 'uncollapsed' then 
			--valid
		elseif args['class'] == '' then
			table.insert
		else
			table.insert
		end
	end
	
	if isnotempty(args['stack']) then
		table.insert
	end
	
	-- required parameters
	for i, k in ipairs do
		if args[k] == nil then args[k] = '}' end
	end
	-- vcard for stadium
	if isnotempty(args['경기장']) then
		args['경기장'] = tostring(mw.html.create('span'):addClass('location'):wikitext(args['경기장']))
	end

	-- placement of stadium and location information
	if isnotempty(args['location']) then
		location = args['location']
		if isnotempty(args['경기장']) then
			table.insert
		end
	elseif isnotempty(args['경기장']) then
		location = args['경기장']
	end

	-- remaining extra information
	for i, k in ipairs do
		if isnotempty(args[k]) then
			table.insert
		end
	end
	
	-- 득점
	local scorestr = ''
	if args['score1'] or args['score2'] then
		scorestr = (args['score1'] or '0') .. '&ndash;' .. (args['score2'] or '0')
	elseif args['득점'] then
		scorestr = args['득점']
	end
	if args['scorenote'] then
		scorestr = scorestr .. '' .. args['scorenote']
	end
	
	-- notes
	if isnotempty(args['note']) then
		table.insert
	end
	if isnotempty(args['seealso']) then
		table.insert
	end

	-- check if this is a one row table
	if class == '' or class == 'uncollapsed' then
		class = ''
	elseif #extra > 0 or #notes > 0 or isnotempty(args['시간']) or isnotempty(args['report']) or 
		isnotempty(args['goals1']) or isnotempty(args['goals2']) or
		isnotempty(args['penalties1']) or isnotempty(args['penalties2']) or
		isnotempty(args['shootout1']) or isnotempty(args['shootout2']) then
	elseif class == 'collapsible collapsed' or class == 'mw-collapsible mw-collapsed' then
		class = ''
	end
	
	-- Start box
	local root = 
		mw.html.create('div')
	root:tag('span')
	root:newline
	
	-- Start table
	local rtable = root:tag('table')

	local row = rtable:tag('tr'):css
	-- date and round
	local cell = row:tag('td')
	if isnotempty(args['날짜']) then
		cell:tag('span')
		cell:wikitext(' ')
	end
	if isnotempty(args['라운드']) then
		cell:wikitext(small(args['라운드']))
	end
	-- 팀1
	row:tag('td')
	-- 득점
	row:tag('td')
	-- 팀2
	row:tag('td')
	-- location, 경기장
	row:tag('td')

	if #extra > 0 or isnotempty(args['시간']) or isnotempty(args['report']) or 
		isnotempty(args['goals1']) or isnotempty(args['goals2']) then
		local row = rtable:tag('tr'):css:css
		-- 시간
		row:tag('td')
		row:newline	
		-- 골1
		row:tag('td')
		row:newline
		-- 리포트
		row:tag('td')
		row:newline
		-- 골2
		row:tag('td')
		row:newline
		-- 장소, 경기장
		row:tag('td')
	end

	if isnotempty(args['penalties1']) or isnotempty(args['penalties2']) then
		row = rtable:tag('tr')
		row:tag('td'):attr
		row:tag('td'):attr:css:wikitext(bold(labels['penalties']))
		row:tag('td'):attr
		row = rtable:tag('tr'):css:css
		row:newline
		row:tag('td')
		row:newline
		row:tag('td')
		row:newline
		row:tag('td')
		row:newline
	elseif isnotempty(args['shootout1']) or isnotempty(args['shootout2']) then
		row = rtable:tag('tr')
		row:tag('td'):attr
		row:tag('td'):attr:css:wikitext(bold(labels['shootout']))
		row:tag('td'):attr
		row = rtable:tag('tr'):css:css
		row:newline
		row:tag('td')
		row:newline
		row:tag('td')
		row:newline
		row:tag('td')
		row:newline
	end
	
	if #notes > 0 then
		row = rtable:tag('tr'):css
		row:tag('td')
		row:newline
	end
	
	local trackstr = (#tracking > 0) and table.concat or ''
	if #preview > 0 and frame:preprocess( "" ) == "" then
		trackstr = tostring(mw.html.create('div')
	end
	
	return tostring(root) .. trackstr
end