-- Sandbox, do not delete

local getArgs = require('Module:Arguments').getArgs
local p = {}

local function getCountry(country)
	local title = mw.title.new(country)
	
	if not title or not title.exists then
		return country
	end
	
	return '[[' .. country .. ']]'
end

local function getTimespan(timespan)
	return ' (' .. timespan .. ')'
end

local function getImage(image)
	local file = nil

	if string.match(image, '.-%.') then
		file = mw.getCurrentFrame():expandTemplate{title = 'flagicon image', args = {image}}
	elseif string.match(image, '.- %(.-%)') then
		local country, var = string.match(image,'(.-) %((.-)%)')
		file = mw.getCurrentFrame():expandTemplate{title = 'flagdeco', args = {country, var, noredlink = 'y'}}
	else
		file = mw.getCurrentFrame():expandTemplate{title = 'flagdeco', args = {image, noredlink = 'y'}}
	end

	return file
end

function p.main(frame)
	local args = getArgs(frame)
	local hasFlags = false
	local entries = {}
	local i = 1
	local keyHandles = {
		[''] = getCountry,
		['date'] = getTimespan,
		flag = getImage
	}

	for i, entry in ipairs(args) do
		local country
		local timespan
		local flag
		local data = {}
		
		for line in entry:gmatch('[^\n]+') do
			line = mw.text.trim(line)
			
			local key, val = line:match('^([a-z]*):? *(.*)$')
			
			if keyHandles[key] then
				data[key] = keyHandles[key](val)
			else
				return require('Module:Error').error{'Invalid key ' .. key .. ' in argument ' .. i}
			end
		end
		
		if not data[''] then
			return require('Module:Error').error{'A country is required in argument ' .. i}
		end
		
		if not data['date'] then
			return require('Module:Error').error{'A date is required in argument ' .. i}
		end
	
		if data.flag then
			hasFlags = true
		end
		
		table.insert(entries, data)
	
		i = i + 1
	end
	
	local outTable = mw.html.create('table')
		:css({
			padding = '5px',
			float = args.float or 'left',
			['background-color'] = '#f8f9fa',
			border = '1px solid #aaa',
			width = '20em',
			['font-size'] = '90%'
		})

	outTable:tag('tr')
		:tag('th')
			:attr('colspan', hasFlags and 2 or 1)
			:css({
				['text-align'] = 'center',
				['font-size'] = 'larger',
				['font-weight'] = 'bold'
			})
			:wikitext(args.title and args.title or 'Historical affiliations')

	for i, entry in ipairs(entries) do
		local row = outTable:tag('tr')
		
		if entry.flag then
			row:tag('td')
				:css('vertical-align', 'top')
				:wikitext(entry.flag)
		elseif hasFlags then
			row:tag('td')
		end
				
		row:tag('td')
			:css({
				width = '100%',
				['vertical-align'] = 'top'
			})
			:wikitext(entry[''] .. entry['date'])
	end

	return tostring(outTable)
end

return p