-- Style for football tables
local pp = {}

function pp.header(t,Args,p_sub,pos_label,group_col,VTE_text,full_table,results_header_txt)
	-- Load relevant modules
	local yesno = require('Module:Yesno')
	
	-- Create table header
	-- Pre stuff
	local team_width = Args['teamwidth'] or '190'
	local sort_text = yesno(Args['sortable_table'] or 'no') and ' sortable' or ''
	local show_played = not yesno(Args['hide_played'] or 'no')
	local rounds_won = yesno(Args['show_rw'] or Args['rounds_won'] or 'no')
	table.insert(t,'{| class="wikitable'..sort_text..'" style="text-align:center;"\n')            			-- Open table
	-- Table title
	if Args['title'] or Args['table_header'] then
		table.insert(t,'|+ ' .. (Args['title'] or Args['table_header']) .. '\n')
	end
	-- Custom header options
	local played_head_text = Args['pld_header'] or '<abbr title="Played">Pld</abbr>'
	local tie_head_text = Args['tie_header'] or '<abbr title="Tie">T</abbr>'
	local group_head_text = Args['group_header'] or '<abbr title="Group">Grp</abbr>'
	local team_head_text = Args['team_header'] or 'Team'
	local bonus_head_text = Args['bonus_header'] or '<abbr title="Bonus points">BP</abbr>'
	local loss_first = Args['loss_before_tie'] or true
	-- What to rank the teams by
	local ranking_style = Args['ranking_style'] or 'perc'
	local show_points, show_perc = false
	ranking_style = string.lower(ranking_style)
	if ranking_style=='w' or ranking_style=='win' or ranking_style=='wins' then
		-- Based on wins
	elseif ranking_style=='perc' or ranking_style=='percentage' or ranking_style=='%' then
		-- Based on percentage
		show_perc = true
	elseif ranking_style=='percpts' or ranking_style=='%pts' then
		-- Based on percentage and points
		show_perc = true
		show_points = true
	else
		-- Based on points
		show_points = true
	end
	local show_bonus_points = yesno(Args['show_bonus_points'] or 'no')
	local show_tie = yesno(Args['show_tie'] or 'no')
	-- Use points instead of goals for/against
	local for_against_style = Args['for_against_style'] or 'goals'
	local fa_letter, fa_word_sing, fa_word_plur
	local hide_for_against = false
	-- First convert to lower case if it is a string
	for_against_style = string.lower(for_against_style)
	if for_against_style=='g' or for_against_style=='goal' or for_against_style=='goals' then
		fa_letter = 'G'
		fa_word_sing = 'Goal'
		fa_word_plur = 'Goals'
	elseif for_against_style=='p' or for_against_style=='point' or for_against_style=='points' then
		fa_letter = 'P'
		fa_word_sing = 'Point'
		fa_word_plur = 'Points'
	elseif for_against_style=='r' or for_against_style=='run' or for_against_style=='runs' then
		fa_letter = 'R'
		fa_word_sing = 'Run'
		fa_word_plur = 'Runs'
	elseif for_against_style=='none' then
		hide_for_against = true
	else
		fa_letter = 'G'
		fa_word_sing = 'Goal'
		fa_word_plur = 'Goals'
	end
	-- Whether to use goal ratio (goal average) instead
	local do_ratio = yesno(Args['use_goal_ratio'] or 'no')
	local do_average = yesno(Args['use_goal_average'] or 'no')
	
	-- Whether to use goal percentage instead
	local do_percentage = yesno(Args['use_goal_percentage'] or Args['use_point_percentage'] or 'no')
	
	-- Whether to use goals scored instead
	local do_scored = yesno(Args['use_goals_scored'] or 'no')
	
	-- Whether to show totals instead of conference and overall
	local only_totals = yesno(Args['only_totals'] or 'no')
	
	-- Whether to show totals instead of conference and overall
	local only_conference = yesno(Args['only_conference'] or 'no')
	
	-- Whether to show for against/totals instead of home/away for/against
	local only_fa_totals = yesno(Args['only_fa_totals'] or 'yes')

	-- Use games behind header
	local show_GB = yesno(Args['show_GB'] or 'no')
	
	-- Spacer style
	local sps = only_totals and '' or only_conference and '' or ' style="border-width:1px 1px 1px 3px;"'
	
	-- Initialize
	local tt = {}
	tt.count = 0 		-- Up by one after every call
	tt.tab_text = t		-- Actual text
	-- Actual headers
	if pos_label ~= nil then
		tt = p_sub.colhead(tt,28,pos_label)									-- Position col
	end
	-- Add group header
	if full_table and group_col then
		tt = p_sub.colhead(tt,28,group_head_text)			-- Group col
	end
	tt = p_sub.colhead(tt,team_width,team_head_text..VTE_text)				-- Team col
	if show_played then
		tt = p_sub.colhead(tt,28,played_head_text)							-- Matches played col
	end
	if full_table then
		local lbls = only_totals and {{'', 'Total '}} or only_conference and {{'', 'Conference '}} or {{'C', 'Conference '}, {'', 'Total '}}
		for k,v in ipairs(lbls) do
			local apre, tpre = v[1], v[2]
			tt = p_sub.colhead(tt,'28'..sps,'<abbr title="'..tpre..'won">'..apre..'W</abbr>')				-- Win col
			if loss_first then
				tt = p_sub.colhead(tt,28,'<abbr title="'..tpre..'lost">'..apre..'L</abbr>')			-- Loss col
				if show_tie then
					tt = p_sub.colhead(tt,28,'<abbr title="'..tpre..'tied">'..apre..'T</abbr>')		-- tie col
				end
			else
				if show_tie then
					tt = p_sub.colhead(tt,28,'<abbr title="'..tpre..'tied">'..apre..'T</abbr>')		-- tie col
				end
				tt = p_sub.colhead(tt,28,'<abbr title="'..tpre..'lost">'..apre..'L</abbr>')			-- Loss col
			end
			if rounds_won then
				tt = p_sub.colhead(tt,28,'<abbr title="'..tpre..'rounds won">'..apre..'RW</abbr>')  -- Rounds won
			end
			if not hide_for_against and not only_fa_totals then
				tt = p_sub.colhead(tt,28,'<abbr title="'..tpre..fa_word_plur..' for">'..apre..fa_letter..'F</abbr>')		-- For col
				tt = p_sub.colhead(tt,28,'<abbr title="'..tpre..fa_word_plur..' against">'..apre..fa_letter..'A</abbr>')	-- Against col
			end
			if show_perc then
				if apre=="" then
					tt = p_sub.colhead(tt,36,'<abbr title="Win percentage">'..apre..'PCT</abbr>')
				else
					tt = p_sub.colhead(tt,36,'<abbr title="'..tpre..'win percentage">'..apre..'PCT</abbr>')
				end
			end
			if show_GB and tpre=="Conference " then -- Games behind header
				tt = p_sub.colhead(tt,28,'<abbr title="Games behind">GB</abbr>')
			end
		end
		if not hide_for_against then
			local lsps = sps
			if only_fa_totals then
				tt = p_sub.colhead(tt,'28','<abbr title="'..fa_word_plur..' for">'..fa_letter..'F</abbr>')		-- For col
				tt = p_sub.colhead(tt,'28','<abbr title="'..fa_word_plur..' against">'..fa_letter..'A</abbr>')	-- Against col
				lsps = ''
			end
			if do_ratio or do_average then
				local ratio_word = do_ratio and ' ratio' or ' average'
				local ratio_letter = do_ratio and 'R' or 'Av'
				tt = p_sub.colhead(tt,'28'..lsps,'<abbr title="'..fa_word_sing..ratio_word..'">'..fa_letter..ratio_letter..'</abbr>')	-- Ratio col
			elseif do_percentage then
				tt = p_sub.colhead(tt,'28'..lsps,'<abbr title="'..fa_word_sing..' percentage">%</abbr>')			-- Percentage col
			elseif do_scored then
				tt = p_sub.colhead(tt,'28'..lsps,'<abbr title="'..fa_word_plur..' scored">'..fa_letter..'S</abbr>')	-- Scored col
			else
				tt = p_sub.colhead(tt,'28'..lsps,'<abbr title="'..fa_word_sing..' difference">'..fa_letter..'D</abbr>')	-- Difference col
			end
		end
	end
	if show_bonus_points then
		tt = p_sub.colhead(tt,28,bonus_head_text)			-- Bonus points col
	end
	if show_points then
		tt = p_sub.colhead(tt,28,'<abbr title="Points">Pts</abbr>')					-- Points col
	end
	if full_table then
		tt.count = tt.count+1
		table.insert(tt.tab_text,results_header_txt)
	end
	
	return tt
end

function pp.row(frame,t,Args,p_sub,notes_exist,hth_id_list,full_table,rand_val,team_list,team_code_ii,ii_start,ii_end,ii_fw,bg_col,N_teams,ii,ii_show)
	-- Build the inner parts of individual rows
	
	-- Sub-module usage
	local mm = require('Module:Math')
	local yesno = require('Module:Yesno')
	
	-- Get custom/default options for in table
	local cwin_points = tonumber(Args['cwinpoints']) or tonumber(Args['winpoints']) or 3
	local ncwin_points = tonumber(Args['ncwinpoints']) or tonumber(Args['winpoints']) or 3
	local tie_points = tonumber(Args['tiepoints'])			or 1
	local loss_points = tonumber(Args['losspoints'])			or 0
	local rw_points = tonumber(Args['rwpoints'])				or 1
	
	-- Order of ties and losses --
	local loss_first = Args['loss_before_tie']                 or true	

	-- Optional rounds won
	local rounds_won = yesno(Args['show_rw'] or Args['rounds_won'] or 'no')
	
	-- Get some input
	local cwins = (tonumber(Args['cwin_'..team_code_ii]) or 0)
	local ncwins = (tonumber(Args['ncwin_'..team_code_ii]) or 0)
	local wins = cwins + ncwins
	local cties = (tonumber(Args['ctie_'..team_code_ii]) or 0)
	local ncties = (tonumber(Args['nctie_'..team_code_ii]) or 0)
	local ties = cties + ncties
	local closses = (tonumber(Args['closs_'..team_code_ii]) or 0)
	local nclosses = (tonumber(Args['ncloss_'..team_code_ii]) or 0)
	local losses = closses + nclosses
	local crw = (tonumber(Args['crw_'..team_code_ii]) or 0)
	local ncrw = (tonumber(Args['ncrw_'..team_code_ii]) or 0)
	local rw = crw + ncrw
	
	local cgfor = tonumber(Args['cgf_'..team_code_ii] or Args['cpf_'..team_code_ii] or '0') or '?'
	local ncgfor = tonumber(Args['ncgf_'..team_code_ii] or Args['ncpf_'..team_code_ii] or '0') or '?'
	local gfor = cgfor ~= '?' and ncgfor ~= '?' and (cgfor + ncgfor) or '?'
	local cgaig = tonumber(Args['cga_'..team_code_ii] or Args['cpa_'..team_code_ii] or '0') or '?'
	local ncgaig = tonumber(Args['ncga_'..team_code_ii] or Args['ncpa_'..team_code_ii] or '0') or '?'
	local gaig = cgaig ~= '?' and ncgaig ~= '?' and (cgaig + ncgaig) or '?'
	
	-- Whether to show for against/totals instead of home/away for/against
	local only_fa_totals = yesno(Args['only_fa_totals'] or 'yes')
	if only_fa_totals then
		gfor = gfor  + tonumber(Args['gf_'..team_code_ii] or Args['pf_'..team_code_ii] or '0')
		gaig = gaig  + tonumber(Args['ga_'..team_code_ii] or Args['pa_'..team_code_ii] or '0')
	end
	
	local s_pts = tonumber(Args['adjust_points_'..team_code_ii]) or tonumber(Args['startpoints_'..team_code_ii]) or 0
	local hth_local = Args['hth_'..team_code_ii]				or nil
	-- Then calculate some values
	local matches = wins + ties + losses
	if yesno(Args['only_conference'] or 'no') then
		matches = cwins + cties + closses
	end
	local points = cwin_points*cwins + ncwin_points*ncwins + tie_points*ties + loss_points*losses + rw_points*rw + s_pts
	
	if Args['goalpoints'] and tonumber(gfor) then
		points = points + (tonumber(Args['goalpoints']) or 1)*tonumber(gfor)
	end
	local show_tie = yesno(Args['show_tie'] or 'no')
	
	local win_perc = ''
	local cwin_perc = ''
	local include_ties = yesno(Args['include_ties'] or 'yes')
	if tonumber(matches) == nil or matches == 0 then 
		-- Escape for zero matches
		win_perc = '&mdash;' 
	else
		--Some sports use tie as well
		if include_ties then
			win_perc = mm._precision_format((2*wins + ties) / (2*matches), 3)
		else
			win_perc = mm._precision_format(wins / (matches - ties), 3)
		end
		if losses > 0 then
			-- Drop the leading zero (from the string)
			win_perc = string.sub(win_perc,2,string.len(win_perc))
		end
	end
	if tonumber(cwins+closses) == nil or (cwins+closses+cties) == 0 then 
		-- Escape for zero matches
		cwin_perc = '&mdash;' 
	else
		--Some sports use tie as well
		if include_ties then
			cwin_perc = mm._precision_format((2*cwins + cties) / (2*(cwins+cties+closses)), 3)
		else
			cwin_perc = mm._precision_format(cwins / (cwins+closses), 3)
		end
		if closses > 0 then
			-- Drop the leading zero (from the string)
			cwin_perc = string.sub(cwin_perc,2,string.len(cwin_perc))
		end
	end
	-- Show for/against
	local for_against_style = Args['for_against_style'] or 'goals'
	local hide_for_against = false
	for_against_style = string.lower(for_against_style)
	if for_against_style=='none' then
		hide_for_against = true
	end

	-- Comparison of for against
	local gcomp
	-- Whether to use goal ratio (goal average) or goal percentage instead
	local skip_sign
	if yesno(Args['use_goal_ratio'] or 'no') or yesno(Args['use_goal_average'] or 'no') then
		-- Now it is the goal ratio/goal average
		if (gfor == '?') or (gaig == '?') or (gaig == 0) then
			gcomp = '&mdash;'
		else
			gcomp = mm._precision_format(gfor / gaig, 3)
		end
	elseif yesno(Args['use_goal_percentage'] or 'no') then
		-- Now it is the percentage
		if (gfor == '?') or (gaig == '?') or (gaig == 0) then
			gcomp = '&mdash;'
		else
			gcomp = mm._precision_format(100 * gfor / gaig , 1)
		end
	elseif yesno(Args['use_point_percentage'] or 'no') then
		-- Now it is the point percentage
		if (gfor == '?') or (gaig == '?') or ((gfor + gaig) <= 0) then
			gcomp = '&mdash;'
		else
			gcomp = mm._precision_format(100 * gfor / (gfor + gaig) , 2)
		end
	elseif yesno(Args['use_goals_scored'] or 'no') then
		-- Now it is the goals scored
		if gfor == '?' then
			gcomp = '&mdash;'
		else
			gcomp = gfor
		end
	else
		-- It's goal difference
		if (gfor == '?') or (gaig == '?') then
			gcomp = '&mdash;'
		else
			gcomp = gfor - gaig
			-- Formatting with signs
			if gcomp>0 then
				gcomp='+'..gcomp
			elseif gcomp < 0 then
				gcomp='&minus;'..-gcomp
			end
		end
	end
	
	-- Show games behind
	local show_GB = yesno(Args['show_GB'] or 'no')
	local GB_text = '&mdash;'
	if show_GB then
		local GB_team_no = tonumber(Args['GB_team']) or 1
		if ii == GB_team_no then
			-- Do nothing, it's vs this team
		else
			local wins_GB = (tonumber(Args['cwin_'..team_list[GB_team_no]]) or 0)
			local losses_GB = (tonumber(Args['closs_'..team_list[GB_team_no]]) or 0)
			local ties_GB = (tonumber(Args['ctie_'..team_list[GB_team_no]]) or 0)
			local GB_num = (wins_GB-cwins+closses-losses_GB)/2 + (ties_GB - cties)
			-- Display options
			if GB_num >0 then
				-- Indicates trailing GB_team
				GB_text = GB_num
			elseif GB_num == 0 then
				-- Equal, do nothing to get dash
			else 
				-- Ahead of GB team, should be noted by plus (instead of minus that comes from formula)
				GB_text = '+'..-GB_num
			end
		end
	end

	-- Some local vars	
	local hth_string
	local tt_return = p_sub.hth(frame,Args,full_table,hth_id_list,hth_local,notes_exist,team_list,team_code_ii,ii_start,ii_end,rand_val)
	hth_string = tt_return.str
	hth_id_list = tt_return.list
	notes_exist = tt_return.notes_exist
	
	-- What to rank the teams by
	local ranking_style = Args['ranking_style'] or 'perc'
	local rank_points, rank_perc = false
	local win_fw, win_string
	ranking_style = string.lower(ranking_style)
	if ranking_style=='w' or ranking_style=='win' or ranking_style=='wins' then
		-- Based on wins
		win_fw = 'font-weight: bold;'
		win_string = hth_string
	elseif ranking_style=='perc' or ranking_style=='percentage' or ranking_style=='%' then
		-- Based on percentage
		rank_perc = true
		win_fw=ii_fw
		win_string = ''
	elseif ranking_style=='percpts' or ranking_style=='%pts' then
		-- Based on percentage and points
		rank_perc = true
		rank_points = true
		win_fw=ii_fw
		win_string = ''
	else
		-- Based on points
		rank_points = true
		win_fw=ii_fw
		win_string = ''
	end
	local show_played = not yesno(Args['hide_played'] or 'no')
	local show_bonus_points = yesno(Args['show_bonus_points'] or 'no')
	-- Whether to show totals instead of home and away
	local only_totals = yesno(Args['only_totals'] or 'no')
	-- Whether to show totals instead of home and away
	local only_conference = yesno(Args['only_conference'] or 'no')
	-- Spacer style
	local sps = only_totals and '' or only_conference and '' or 'border-width:1px 1px 1px 3px;'
	-- Row building
	if show_played then
		table.insert(t,'| style="'..ii_fw..bg_col..'" |'..matches..'\n') 		-- Played
	end
	if full_table then
		-- Use actual values if wins, ties, and losses are not numeric
		if (cwins == 0 and ncwins == 0 and cties == 0 and ncties == 0 and closses == 0 and nclosses == 0) then
			local function numorval(s)
				return s and ((s == '' and 0) or tonumber(s) or s) or 0
			end
			cwins = numorval(Args['cwin_'..team_code_ii])
			ncwins = numorval(Args['ncwin_'..team_code_ii])
			cties = numorval(Args['ctie_'..team_code_ii])
			ncties = numorval(Args['nctie_'..team_code_ii])
			closses = numorval(Args['closs_'..team_code_ii])
			nclosses = numorval(Args['ncloss_'..team_code_ii])
		end
		local stats = only_totals and {{wins, ties, losses, rw, gfor, gaig}} or 
			only_conference and {{cwins, cties, closses, crw, cgfor, cgaig, cwin_perc}} or
			{{cwins, cties, closses, crw, cgfor, cgaig, cwin_perc}, {wins, ties, losses, rw, gfor, gaig, win_perc}}
		local first_pass = true
		for k,v in ipairs(stats) do
			table.insert(t,'| style="'..sps..win_fw..bg_col..'" |'..(v[1])..win_string..'\n') 			-- Won
		
			if loss_first then
				table.insert(t,'| style="'..ii_fw..bg_col..'" |'..(v[3])..'\n') 	-- Lost
				if show_tie then
					table.insert(t,'| style="'..ii_fw..bg_col..'" |'..(v[2])..'\n') 		-- tied
				end
			else
				if show_tie then
					table.insert(t,'| style="'..ii_fw..bg_col..'" |'..(v[2])..'\n') 		-- tied
				end
				table.insert(t,'| style="'..ii_fw..bg_col..'" |'..(v[3])..'\n') 	-- Lost
			end
			if rounds_won then
				table.insert(t,'| style="'..ii_fw..bg_col..'" |'..(v[4])..'\n')         -- Rounds won
			end
			if not hide_for_against and not only_fa_totals then
				table.insert(t,'| style="'..ii_fw..bg_col..'" |'..(v[5])..'\n') 		-- GF
				table.insert(t,'| style="'..ii_fw..bg_col..'" |'..(v[6])..'\n')		-- GA
			end
			if rank_perc then
				if first_pass then
					table.insert(t,'| style="font-weight: bold;'..bg_col..'" | '..(v[7])..hth_string..'\n')
				else
					table.insert(t,'| style="'..bg_col..'" | '..(v[7])..'\n')
				end
			end
			if show_GB and first_pass then
				table.insert(t,'| style="'..ii_fw..bg_col..'" |'..GB_text..'\n')  -- GB
			end
			first_pass = false
		end
		if not hide_for_against then
			local lsps = sps
			if only_fa_totals then
				table.insert(t,'| style="'..ii_fw..bg_col..'" |'..gfor..'\n') 	-- GF
				table.insert(t,'| style="'..ii_fw..bg_col..'" |'..gaig..'\n')	-- GA
				lsps = ''
			end
			table.insert(t,'| style="'..lsps..ii_fw..bg_col..'" |'..gcomp..'\n')      -- Goal comparison
		end
	end
	if show_bonus_points then
		if s_pts < 0 then
			table.insert(t,'| style="'..bg_col..'" | &minus;'..-s_pts..'\n')
		else
			table.insert(t,'| style="'..bg_col..'" | '..s_pts..'\n')
		end
	end
	if rank_points then
		-- Add &minus; for negative point totals
		if points<0 then
			table.insert(t,'| style="font-weight: bold;'..bg_col..'" | &minus;'..-points..hth_string..'\n')
		else
			table.insert(t,'| style="font-weight: bold;'..bg_col..'" | '..points..hth_string..'\n')
		end
	end
	return {t=t, notes_exist=notes_exist, hth_id_list=hth_id_list}
end

function pp.status(Args)
	-- Declare status options
	-- ------------------------------------------------------------
	-- NOTE: If you add to status_code, also add to status_called and status_letters!!
	-- Or functionality will be compromised
	-- ------------------------------------------------------------
	local status_code, status_called = {}, {}
	status_code = {	A='Advance to a further round', C='Champion', D='Disqualified', 
		E='Eliminated', G='Guest', H='Host', O='Play-off winner', P='Promoted', Q='Qualified for the phase indicated',
		R='Relegated', T='Qualified, but not yet for the particular phase indicated'}
	local status_letters = (Args['status_order'] or '') .. 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
	
	-- Status position (before or after read and default)
	local stat_pos_val = string.lower(Args['status_pos'] or '')
	local status_position = 'after' 	-- Default location
	if stat_pos_val=='before' then
		status_position = 'before'
	elseif stat_pos_val=='after' then
		status_position = 'after'
	end
	-- Read in custom status options
	for l in mw.text.gsplit(status_letters, '') do
		status_called[l] = false
		status_code[l] = status_code[l] or '?'
		status_letters = mw.ustring.gsub(status_letters, '(' .. l ..'.-)' .. l, '%1')

		if Args['status_text_' .. l] then
			status_code[l] = Args['status_text_' .. l]
		end
	 end
	
	return {code=status_code, called=status_called, letters=status_letters, position=status_position}
end

return pp