local infoboxStyle = mw.loadData('Module:WPMILHIST Infobox style')
local templatestyles = 'Module:Infobox military conflict/styles.css'

local IMC = {}
IMC.__index = IMC

local param_ko = {
	['날짜'] = 'date',
	['장소'] = 'place',
	['좌표'] = 'coordinates',
	['배경'] = 'action',
	['상태'] = 'status',
	['결과'] = 'result',
	['영토'] = 'territory',
	['전역상자'] = 'campaignbox',
	['너비'] = 'width',
	['분쟁'] = 'conflict',
	['전체'] = 'partof',
	['그림'] = 'image',
	['그림2'] = 'image2', -- kowiki-specific
	['그림크기'] = 'image_size',
	['그림크기2'] = 'image_size2', -- kowiki-specific
	['크기2'] = 'image_size2', -- kowiki-specific
	['기본'] = 'sidedefault',
	['대체설명'] = 'alt',
	['대체설명2'] = 'alt2', -- kowiki-specific
	['설명'] = 'caption',
	['설명2'] = 'caption2', -- kowiki-specific
	['교전국머리말'] = 'combatants_header',
	['기타'] = 'notes',
	--[''] = 'map_type',
	--[''] = 'map_relief',
	['지도크기'] = 'map_size',
	--[''] = 'map_mark',
	--[''] = 'map_marksize',
	--[''] = 'map_label',
	['대체지도설명'] = 'map_alt',
	['지도설명'] = 'map_caption',
	['교전국1'] = 'combatant1',
	['교전국2'] = 'combatant2',
	['교전국3'] = 'combatant3',
	['교전국4'] = 'combatant4',
	['교전국5'] = 'combatant5',
	['교전국1a'] = 'combatant1a',
	['교전국2a'] = 'combatant2a',
	['교전국3a'] = 'combatant3a',
	['교전국4a'] = 'combatant4a',
	['교전국5a'] = 'combatant5a',
	['교전국1b'] = 'combatant1b',
	['교전국2b'] = 'combatant2b',
	['교전국3b'] = 'combatant3b',
	['교전국4b'] = 'combatant4b',
	['교전국5b'] = 'combatant5b',
	['교전국1c'] = 'combatant1c',
	['교전국2c'] = 'combatant2c',
	['교전국3c'] = 'combatant3c',
	['교전국4c'] = 'combatant4c',
	['교전국5c'] = 'combatant5c',
	['교전국1d'] = 'combatant1d',
	['교전국2d'] = 'combatant2d',
	['교전국3d'] = 'combatant3d',
	['교전국4d'] = 'combatant4d',
	['교전국5d'] = 'combatant5d'

function IMC:renderPerCombatant
	prefix = prefix or ''
	suffix = suffix or ''
	local colspans = {}
	
	-- This may result in colspans[1] getting set twice, but
	-- this is no big deal. The second set will be correct.
	local lastCombatant = 1
	
	for i = 1,self.combatants do
		if self.args[prefix .. i .. suffix] then
			colspans[lastCombatant] = i - lastCombatant
			lastCombatant = i
		end
	end

	local jointText = self.args[prefix .. (self.combatants + 1) .. suffix]
	
	if headerText and (colspans[1] or jointText) then
		builder:tag('tr')
	end

	-- The only time colspans[1] wouldn't be set is if no
	-- combatant has a field with the given prefix and suffix.
	if colspans[1] then
		-- Since each found argument set the colspan for the previous
		-- one, the final one wasn't set above, so set it now.
		colspans[lastCombatant] = self.combatants - lastCombatant + 1
		builder = builder:tag('tr')
		for i = 1,self.combatants do
			-- At this point, colspans[i] will be set for i=1 unconditionally, and for
			-- any other value of i where self.args[prefix .. i .. suffix] is set.
			if colspans[i] then
				builder:tag('td')
					-- don't bother emitting colspan="1"
					-- no border on the right of the rightmost column
					-- no padding on the left of the leftmost column
					-- don't show the border if we're directly under a header
			end
		end
	end

	if jointText then
		builder:tag('tr')
				-- don't show the border if we're directly under a header
	end
end

function IMC:renderHeaderTable(builder)
	builder = builder:tag('table')

	if self.args.date then
		builder:tag('tr')
	end

	builder = builder:tag('tr')
	if self.args.coordinates then
		builder:wikitext('' .. self.args.coordinates)
	end
	builder = builder:done:done

	-- only for "Putsch"
 if self.args.action then
		builder:tag('tr')
	end

	if self.args.status or self.args.result then
		builder:tag('tr')
	end

	if self.args.territory then
		builder:tag('tr')
	end
end

function IMC:render
	local builder = mw.html.create
	if self.args.campaignbox then
		-- this should be the same as using 
		builder = builder:tag('div')
	end
	builder = builder:tag('table')

	builder:tag('tr')
	if self.args.partof then
		builder:tag('tr')
	end
	if self.args.image then
		builder:tag('tr')
					require('Module:InfoboxImage').InfoboxImage{args = {
						image = self.args.image,
						size = self.args.image_size,
						sizedefault = 'frameless',
						upright = 1,
						alt = self.args.alt
					self.args.caption and '' or '',
					self.args.caption or ''
				))
	end

	-- kowiki-specific conditional statement
	if self.args.image2 then
		builder:tag('tr')
					require('Module:InfoboxImage').InfoboxImage{args = {
						image = self.args.image2,
						size = self.args.image_size2,
						sizedefault = 'frameless',
						upright = 1,
						alt = self.args.alt2
					self.args.caption2 and '' or '',
					self.args.caption2 or ''
				))
	end

	self:renderHeaderTable(builder:tag('tr'):tag('td'):attr)
	self:renderPerCombatant
	-- can be un-hardcoded once gerrit:165108 is merged
	for _,v in ipairs{'a','b','c','d'} do
		self:renderPerCombatant
	end
	
	self:renderPerCombatant
 for _,v in ipairs{'a','b','c','d'} do
		self:renderPerCombatant
	end

	self:renderPerCombatant
	self:renderPerCombatant
	self:renderPerCombatant
	self:renderPerCombatant
	self:renderPerCombatant

	if self.args.notes then
		builder:tag('tr')
	end
	if self.args['지도'] then
		builder:tag('tr')
					require('모듈:InfoboxImage').InfoboxImage{args = {
						["그림"] = self.args['지도'],
						["크기"] = self.args['지도크기'] or self.args['그림크기'] or '300px',
						["기본"] = 'frameless',
						upright = 1,
						alt = self.args['대체지도설명']
					self.args['지도설명'] and '' or '',
					self.args['지도설명'] or ''
					))
	end
	if self.args.map_type then
		builder:tag('tr')
					self.args.map_type,
					relief = self.args.map_relief,
					coordinates = self.args.coordinates,
					width = self.args.map_size or 220,
					float = 'center',
					border = 'none',
					mark = self.args.map_mark,
					marksize = self.args.map_marksize or 8,
					label = self.args.map_label,
					alt = self.args.map_alt,
					caption = self.args.map_caption or ('장소: ' 
						.. (require('Module:Location map').data))
	end
	builder = builder:done
	if self.args.campaignbox then
		builder = builder:done
	end
	return builder
end

function IMC.new
	if not args then
		args = require('Module:Arguments').getArgs
	end

	for kk, vv in pairs(param_ko) do
		if vv ~= '' then
			local newVal = args[kk]
			if newVal ~= nil and newVal ~= '' then
				args[param_ko[kk]] = args[kk]
			end
		end
	end

	local obj = {
		frame = frame,
		args = args

	-- until gerrit:165108 is merged, there's still a cap on combatants, but as soon as it merges, we can update this little bit of code to uncap it
	-- also, don't try to make this more efficient, or references could be in the wrong order
	obj.combatants = 2
	for _,v in ipairs{'', 'a', 'b', 'c', 'd'} do
		for i = 1,5 do
			if args['combatant' .. i .. v] then
				obj.combatants = math.max
			end
		end
	end

	return setmetatable
end

local p = {}

function p.main(frame)
	return frame:extensionTag{ name = 'templatestyles', args = { src = templatestyles} } .. tostring(IMC.new(frame):render)
end