local HTMLcolor = mw.loadData( 'Module:Color contrast/colors' )

-- EpisodeTable class
-- The main class.

local contrast_ratio = require('Module:Color contrast')._ratio
local EpisodeTable = {}

function EpisodeTable.cell
	local cell = mw.html.create('th')
	
	-- Width
	local cell_width
	if width == 'auto' then
		cell_width = 'auto'
	elseif tonumber(width) ~= nil then
		cell_width = width .. '%'
	else
		cell_width = nil
	end
	
	-- Cell
	cell:attr
	
	-- Reference
	if reference and reference ~= '' then
		cell:wikitext("&#8202;" .. EpisodeTable.reference)
	end
	
	return cell
end

function EpisodeTable.reference
	local link1_cr = contrast_ratio{'#0645AD', background or '#CCCCFF', ['error'] = 0}
	local link2_cr = contrast_ratio{'#0B0080', background or '#CCCCFF', ['error'] = 0}
	
	local refspan = mw.html.create('span')
	
	if link1_cr < 7 or link2_cr < 7 then
		refspan
	end
	
	return tostring(refspan)
end

function EpisodeTable.abbr
	local abbr = mw.html.create('abbr')
	return tostring(abbr)
end

function EpisodeTable.part
	local row = mw.html.create('tr')
	
	if (args.c == nil or args.c == '') then args.c = '#CCCCFF' end
	
	local black_cr = contrast_ratio{args.c or '#CCCCFF', 'black', ['error'] = 0}
	local white_cr = contrast_ratio{'white', args.c or '#CCCCFF', ['error'] = 0}
	
	local partTypes = {
	
	local displaytext = ''
	local isAnyPartSet = false
	
	for k,v in pairs(partTypes) do
		if args[v[1]] then
			isAnyPartSet = true
			displaytext = v[2] .. ' ' .. args[v[1]]
		end
	end
	if args.subtitle then
		displaytext = displaytext .. ((isAnyPartSet and ': ' or '') .. args.subtitle)
	end

	local plainText = require('Module:Plain text')._main
	local displayTextAnchor = plainText(displaytext)
	
	row:tag('td')
	
	return tostring(row)
end

function EpisodeTable.new
	args = args or {}
	local categories = ''
	local background = (args.background and args.background ~= '' and args.background ~= '#') and args.background or nil
	
	-- Add # to background if necessary
	if background ~= nil and HTMLcolor[background] == nil then
		background = '#'..(mw.ustring.match(background, '^[%s#]*([a-fA-F0-9]*)[%s]*$') or '')
	end
	
	-- Default widths noted by local consensus
	local defaultwidths = {};
	defaultwidths.overall = 5;
	defaultwidths.overall2 = 5;
	defaultwidths.season = 5;
	defaultwidths.series = 5;
	defaultwidths.prodcode = 7;
	defaultwidths.viewers = 10;
	
	-- Create episode table
	local root = mw.html.create('table')
	
	-- Table width
	local table_width = string.gsub
	if args.total_width == 'auto' or args.total_width == '' then
		table_width = 'auto'
	elseif tonumber(table_width) ~= nil then
		table_width = table_width .. '%'
	else
		table_width = '100%'
	end
	
	root
	
	-- Caption
	if args.show_caption then
		-- Visible caption option, with a tracking category
		root:tag('caption'):wikitext(args.caption)
		categories = categories .. 'Category:Articles using Template:Episode table with a visible caption'
	elseif args.caption then
		-- If a visible caption isn't defined, then default to the screenreader-only caption
		root:tag('caption'):wikitext
	end
	
	-- Colour contrast; add to category only if it's in the mainspace
	local title = mw.title.getCurrentTitle
	local black_cr = contrast_ratio{background, 'black', ['error'] = 0}
	local white_cr = contrast_ratio{'white', background, ['error'] = 0}
	
	if title.namespace == 0 and (args.background and args.background ~= '' and args.background ~= '#') and black_cr < 7 and white_cr < 7 then
		categories = categories .. 'Category:Articles using Template:Episode table with invalid colour combination' 
	end
	
	-- Main row
	local mainRow = root:tag('tr')
	mainRow
	
	-- Cells
	do
		local used_season = false
		local country = args.country ~= '' and args.country ~= nil
		local viewers = (country and args.country or '') .. ' ' .. (country and 'v' or 'V') .. 'iewers' ..
			((not args.viewers_type or args.viewers_type ~= '') and '(' .. (args.viewers_type or 'millions') .. ')' or '')
		
		local cellNames = {
				((args.season or args.series or args.EpisodeNumber2 or args.EpisodeNumber2Series or args.forceoverall) and '", "") or tostring(root)) .. categories
end

-- Exports

local p = {}

function p.main(frame)
	local args = require('Module:Arguments').getArgs(frame, {
		removeBlanks = false,
		wrappers = 'Template:Episode table'
	return EpisodeTable.new
end

function p.part(frame)
	local args = require('Module:Arguments').getArgs(frame, {
		removeBlanks = false,
		wrappers = 'Template:Episode table/part'
	return EpisodeTable.part
end

function p.ref(frame)
	local args = require('Module:Arguments').getArgs(frame, {
		removeBlanks = false,
	return EpisodeTable.reference
end