-- Style for cricket 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 '180'
    local sort_text = yesno(Args['sortable_table'] or 'no') and ' sortable' or ''
    --local show_played = not yesno(Args['hide_played'] or 'no')

	table.insert(t,'{|class="wikitable'..sort_text..'" style="text-align:center;"\n')            			-- Open table

	-- Table title
	if Args['title'] then
        table.insert(t,'|+ ' .. Args['title'] .. '\n')
	end

    --Header specific options
	local team_head_text = Args['team_header'] or 'Team'
    local tie_head_text = Args['tie_header'] or '<abbr title="Tied">T</abbr>'
    local draw_head_text = Args['draw_header'] or '<abbr title="Drawn">D</abbr>'
    local aban_head_text = Args['aban_header'] or '<abbr title="Abandoned">A</abbr>'
    local bat_head_text = Args['bat_header'] or '<abbr title="Batting points">Bat</abbr>'
    local bowl_head_text = Args['bowl_header'] or '<abbr title="Bowling points">Bowl</abbr>'
    local deduct_head_text = Args['deduct_header'] or '<abbr title="Deducted points">Ded</abbr>'
    local pcf_head_text = Args['pcf_header'] or '<abbr title="Points carried forward">PCF</abbr>'
    -- 
    local loss_first = yesno(Args['loss_before_tie']  or 'yes')
    local show_aban = yesno(Args['show_aban'] or 'yes')
    local show_bonus_points = yesno(Args['show_bonus_points'] or 'yes')
    local show_deduct = yesno(Args['show_deductions'] or 'yes')
    local show_pcf = yesno(Args['show_pcf'] or 'yes')

    -- What to rank the teams by
    --local ranking_style = Args['ranking_style'] or 'pts'

    -- 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

    tt = p_sub.colhead(tt, team_width, team_head_text..VTE_text)        -- Team col

    tt = p_sub.colhead(tt,32,'<abbr title="Played">Pld</abbr>')			-- Matches played col
	
	if full_table then

        tt = p_sub.colhead(tt,32,'<abbr title="Won">W</abbr>')			-- Win col
		
        if loss_first then
            tt = p_sub.colhead(tt,32,'<abbr title="Lost">L</abbr>')		-- Loss col
            tt = p_sub.colhead(tt,32,tie_head_text)					    -- Tie col
            tt = p_sub.colhead(tt,32,draw_head_text)					-- Draw col
		else
            tt = p_sub.colhead(tt,32,tie_head_text)					    -- Tie col
            tt = p_sub.colhead(tt,32,draw_head_text)					-- Draw col            
            tt = p_sub.colhead(tt,32, '<abbr title="Lost">L</abbr>')   -- Loss col
        end
        if show_aban then
            tt = p_sub.colhead(tt,32,aban_head_text)	                    --Abandoned col
        end
        if show_bonus_points then
            tt = p_sub.colhead(tt,32,bat_head_text)	                    -- Batting points col
            tt = p_sub.colhead(tt,32,bowl_head_text)	                -- Bowling points col
        end
        if show_deduct then
            tt = p_sub.colhead(tt,32,deduct_head_text)	                -- Deduction col
        end
       if show_pcf then
            tt = p_sub.colhead(tt,32,pcf_head_text)	                -- Points carried forward col
        end
    end

    tt = p_sub.colhead(tt, 32, '<abbr title="Points">Pts</abbr>')       -- Points col
	
	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 win_points = tonumber(Args['winpoints'])            or 16
  	local tie_points = tonumber(Args['tiepoints'])            or 8
    local draw_points = tonumber(Args['drawpoints'])          or 5
	local aban_points = tonumber(Args['abanpoints'])          or 5
	local loss_points = tonumber(Args['losspoints'])          or 0
    local draw_bonus_points = tonumber(Args['drawbonuspoints']) or 3

    -- table options, to match those in the header        
    local loss_first = yesno(Args['loss_before_tie']  or 'yes')
    local show_tie = yesno(Args['show_tie'] or 'yes')
    local show_aban = yesno(Args['show_aban'] or 'yes')
    local show_bonus_points = yesno(Args['show_bonus_points'] or 'yes')
    local show_deduct = yesno(Args['show_deductions'] or 'yes')
    local show_pcf = yesno(Args['show_pcf'] or 'yes')
    -- Get some input
    local wins = tonumber(Args['win_'..team_code_ii])       or 0
	local ties = tonumber(Args['tie_'..team_code_ii])       or 0
	local draws = tonumber(Args['draw_'..team_code_ii])      or 0
 	local losses = tonumber(Args['loss_'..team_code_ii])    or 0
	local abandons = tonumber(Args['aban_'..team_code_ii])  or 0
    local batting = tonumber(Args['bat_'..team_code_ii])    or 0
    local bowling = tonumber(Args['bowl_'..team_code_ii])   or 0
    local deductions = tonumber(Args['ded_'..team_code_ii]) or 0
    local pcf = tonumber(Args['pcf_'..team_code_ii]) or 0
    local drawbonus = tonumber(Args['drawbonus_'..team_code_ii]) or 0

	local hth_local = Args['hth_'..team_code_ii]               or nil  --?
	
	-- Then calculate some values
    local matches = wins + losses + draws + ties + abandons

    local points = win_points*wins + loss_points*losses + tie_points*ties + draw_points*draws + aban_points*abandons + draw_bonus_points*drawbonus + batting + bowling + pcf - deductions
    
    -- 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 'pts'
	local win_fw, win_string, pts_fw, pts_string

    ranking_style = string.lower(ranking_style)
	if ranking_style=='p' or ranking_style=='pts' or ranking_style=='points' then
		-- Based on points
        win_fw = ii_fw

        win_string = ''
		pts_fw = 'font-weight: bold;'
		pts_string = hth_string
	else
		-- Based on wins
        win_fw = 'font-weight: bold;'

        win_string = hth_string
        pts_fw = ii_fw

        pts_string = ''
	end
	
	-- Row building
    table.insert(t,'| style="'..ii_fw..bg_col..'" |'..matches..'\n') 		-- Played

	if full_table then
		-- Use actual values if wins, ties, and losses are not numeric
		if (wins == 0 and ties == 0 and losses == 0 and draws ==0 and abandons == 0) then
            local function numorval(s)
				return s and((s == '' and 0) or tonumber(s) or s) or 0
			end
            wins = numorval(Args['win_'..team_code_ii])
            ties = numorval(Args['tie_'..team_code_ii])
            losses = numorval(Args['loss_'..team_code_ii])
            draws = numorval(Args['draw_'..team_code_ii])
            abandons = numorval(Args['aban_'..team_code_ii])
        end
        table.insert(t,'| style="'..win_fw..bg_col..'" |'..wins..win_string..'\n')  -- Won
        if loss_first then
            table.insert(t,'| style="'..ii_fw..bg_col..'" |'..losses..'\n')         -- Lost
            table.insert(t,'| style="'..ii_fw..bg_col..'" |'..ties..'\n') 	        -- Ties
            table.insert(t,'| style="'..ii_fw..bg_col..'" |'..draws..'\n') 	        -- draws
        else
            table.insert(t,'| style="'..ii_fw..bg_col..'" |'..ties..'\n') 	        -- Ties
            table.insert(t,'| style="'..ii_fw..bg_col..'" |'..draws..'\n') 	        -- draws
            table.insert(t,'| style="'..ii_fw..bg_col..'" |'..losses..'\n')         -- Lost
        end
        if show_aban then
            table.insert(t,'| style="'..ii_fw..bg_col..'" |'..abandons..'\n')         -- Abandonments
        end
	    if show_bonus_points then
            table.insert(t,'| style="'..bg_col..'" | '..batting..'\n')
            table.insert(t,'| style="'..bg_col..'" | '..bowling..'\n')
    	end
    	if show_deduct then 
    	    table.insert(t,'| style="'..bg_col..'" | '..deductions..'\n')
    	end
        if show_pcf then 
    	    table.insert(t,'| style="'..bg_col..'" | '..pcf..'\n')
    	end
	end
	if points<0 then
        table.insert(t,'| style="'..pts_fw..bg_col..'" | &minus;'..-points..pts_string..'\n')
	else
		table.insert(t,'| style="'..pts_fw..bg_col..'" | '..points..pts_string..'\n')
	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='Advances 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
	
	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