local precision = require('Module:Math')._precision

local function stripToNil(text)
	-- If text is a non-empty string, return its trimmed content.
	-- Otherwise, return nothing (text is an empty string or is not a string).
	if type(text) == 'string' then
		return text:match('(%S.-)%s*$')
	end
end

local function isAny
	local months = { 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' }
	for _, month in ipairs(months) do
		if stripToNil(args[month .. suffix]) then
			return true
		end
	end
end

local function makeLabel
	local first
	if isAny then
		first = 'cm'
	else
		if isAny then
			first = 'mm'
		else
			first = (what == 'snow' or
				precision(args['Jan ' .. what .. ' inch'] or '0') < 1)
					and 'cm'
					or 'mm'
		end
	end
	local second = '인치'
	if not stripToNil(args['metric first']) then
		first, second = second, first
	end
	if is_first then
		if stripToNil(args['single line']) then
			first = first .. ' (' .. second .. ')'
		end
	else
		first = second
	end
	return base .. ' ' .. first
end

local function makeSources
	local source1 = stripToNil(args.source) or stripToNil(args['source 1'])
	local source2 = stripToNil(args['source 2']) or stripToNil(args['source2'])
	local result = '|-\n|colspan="14" style="text-align:center;font-size:95%;"|'
	local text
	if source1 or source2 then
		if source1 and source2 then
			text = '출처 1: ' .. source1 .. '\n' .. result .. '출처 2: ' .. source2
		else
			text = '출처: ' .. (source1 and source1 or source2)
		end
	else
		text = frame:expandTemplate({ title = '출처', args = {['날짜'] = stripToNil(args.date)} })
	end
	return result .. text .. '\n|}'
end

local function getDefinitions
	-- Return a list of tables or strings that define each row.
	local navbar = require('Module:Navbar')._navbar
	local function _if
		return stripToNil(args[parm]) and a or b or ''
	end
	local function _ifset
		return stripToNil(args[parm]) and args[parm] or a
	end
	local function _ifany(suffix)
		return isAny
	end
	return {

'{| class="wikitable ' .. _if('open', '', 'mw-collapsible' .. _if) ..
'" style="width:' .. _ifset ..
'; text-align:center; line-height: 1.2em; margin:' ..
_ifset .. ';"' ..
_if('open',
		'\n|+' .. _if .. '의 기후',
'\n|-' ..
'\n!colspan="14" | ' ..
_if('name',
	navbar({_if .. '의 기후', args.name, collapsible=1}),
	_if .. '의 기후'
)
) ..
[=[

]=],

	WANTROW = _ifany(' maximum humidex') and (_ifset('metric first') or _ifset('single line')),
	mode = 'basic',
	group_name = 'maximum humidex',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '최고 불쾌지수 기록',
	annual_mode = 'max',
	WANTROW = _ifany(' record high C') or _ifany(' record high F'),
	mode = 'temperature',
	group_name = 'record high',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '최고 기온 기록 °' .. _if .. _if('single line', ' (°' .. _if .. ')'),
	annual_mode = 'max',
	WANTROW = _ifany(' avg record high C') or _ifany(' avg record high F'),
	mode = 'temperature',
	group_name = 'avg record high',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '평균 월 최고 기온 °' .. _if .. _if('single line', ' (°' .. _if .. ')'),
	annual_mode = 'max',
	WANTROW = _ifany(' high C') or _ifany(' high F'),
	mode = 'temperature',
	group_name = 'high',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '평균 일 최고 기온 °' .. _if .. _if('single line', ' (°' .. _if .. ')'),
	annual_mode = 'avg',
	WANTROW = _ifany(' mean C') or _ifany(' mean F'),
	mode = 'temperature',
	group_name = 'mean',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '일 평균 기온 °' .. _if .. _if('single line', ' (°' .. _if .. ')'),
	annual_mode = 'avg',
	WANTROW = _ifany(' low C') or _ifany(' low F'),
	mode = 'temperature',
	group_name = 'low',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '평균 일 최저 기온 °' .. _if .. _if('single line', ' (°' .. _if .. ')'),
	annual_mode = 'avg',
	WANTROW = _ifany(' avg record low C') or _ifany(' avg record low F'),
	mode = 'temperature',
	group_name = 'avg record low',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '평균 월 최저 기온 °' .. _if .. _if('single line', ' (°' .. _if .. ')'),
	annual_mode = 'min',
	WANTROW = _ifany(' record low C') or _ifany(' record low F'),
	mode = 'temperature',
	group_name = 'record low',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '최저 기온 기록 °' .. _if .. _if('single line', ' (°' .. _if .. ')'),
	annual_mode = 'min',
	WANTROW = _ifany(' chill') and (_ifset('metric first') or _ifset('single line')),
	mode = 'basic',
	group_name = 'chill',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '최저 체감온도 기록',
	annual_mode = 'min',
	WANTROW = _ifany(' precipitation cm') or _ifany(' precipitation mm') or _ifany(' precipitation inch'),
	mode = 'precipitation',
	group_name = 'precipitation',
	color_scheme = _ifset,
	date_mode = true,
	scale_factor = '1',
	prefer_cm = precision(_ifset) < 1,
	label = makeLabel,
	annual_mode = 'sum',
	WANTROW = _ifany(' rain cm') or _ifany(' rain mm') or _ifany(' rain inch'),
	mode = 'precipitation',
	group_name = 'rain',
	color_scheme = _ifset,
	date_mode = true,
	scale_factor = '1',
	prefer_cm = precision(_ifset) < 1,
	label = makeLabel,
	annual_mode = 'sum',
	WANTROW = _ifany(' snow cm') or _ifany(' snow mm') or _ifany(' snow inch'),
	mode = 'precipitation',
	group_name = 'snow',
	prefer_cm = true,
	color_scheme = _ifset,
	date_mode = true,
	scale_factor = '1',
	label = makeLabel,
	annual_mode = 'sum',
	WANTROW = not _ifset('single line') and _ifany(' maximum humidex'),
	mode = 'basic',
	group_name = 'maximum humidex',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '불쾌지수',
	annual_mode = 'max',
	second_line = true,
	WANTROW = not _ifset('single line') and (_ifany(' record high C') or _ifany(' record high F')),
	mode = 'temperature',
	group_name = 'record high',
	second_line = true,
	color_scheme = _ifset,
	scale_factor = '1',
	label = '최고 기온 기록 °' .. _if,
	annual_mode = 'max',
	WANTROW = not _ifset('single line') and (_ifany(' high C') or _ifany(' high F')),
	mode = 'temperature',
	group_name = 'high',
	second_line = true,
	color_scheme = _ifset,
	scale_factor = '1',
	label = '평균 최고 기온 °' .. _if,
	annual_mode = 'avg',
	WANTROW = not _ifset('single line') and (_ifany(' mean C') or _ifany(' mean F')),
	mode = 'temperature',
	group_name = 'mean',
	second_line = true,
	color_scheme = _ifset,
	scale_factor = '1',
	label = '일 평균 기온 °' .. _if,
	show = _if,
	annual_mode = 'avg',
	WANTROW = not _ifset('single line') and (_ifany(' low C') or _ifany(' low F')),
	mode = 'temperature',
	group_name = 'low',
	second_line = true,
	color_scheme = _ifset,
	scale_factor = '1',
	label = '평균 최저 기온 °' .. _if,
	show = _if,
	annual_mode = 'avg',
	WANTROW = not _ifset('single line') and (_ifany(' record low C') or _ifany(' record low F')),
	mode = 'temperature',
	group_name = 'record low',
	second_line = true,
	color_scheme = _ifset,
	scale_factor = '1',
	label = '최저 기온 기록 °' .. _if,
	show = _if,
	annual_mode = 'min',
	WANTROW = not _ifset('single line') and (_ifany(' chill') and _if('metric first')),
	mode = 'basic',
	group_name = 'chill',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '체감온도',
	annual_mode = 'min',
	WANTROW = not _ifset('single line') and (_ifany(' precipitation cm') or _ifany(' precipitation mm') or _ifany(' precipitation inch')),
	mode = 'precipitation',
	group_name = 'precipitation',
	second_line = true,
	color_scheme = _ifset,
	date_mode = true,
	scale_factor = '1',
	prefer_cm = precision(_ifset) < 1,
	label = makeLabel,
	annual_mode = 'sum',
	WANTROW = not _ifset('single line') and (_ifany(' rain cm') or _ifany(' rain mm') or _ifany(' rain inch')),
	mode = 'precipitation',
	group_name = 'rain',
	second_line = true,
	color_scheme = _ifset,
	date_mode = true,
	scale_factor = '1',
	prefer_cm = precision(_ifset) < 1,
	label = makeLabel,
	annual_mode = 'sum',
	WANTROW = not _ifset('single line') and (_ifany(' snow cm') or _ifany(' snow mm') or _ifany(' snow inch')),
	mode = 'precipitation',
	group_name = 'snow',
	second_line = true,
	prefer_cm = true,
	color_scheme = _ifset,
	date_mode = true,
	scale_factor = '1',
	label = makeLabel,
	annual_mode = 'sum',
	WANTROW = _ifany(' precipitation days'),
	mode = 'basic',
	group_name = 'precipitation days',
	color_scheme = _ifset,
	date_mode = true,
	scale_factor = '1',
	label = '평균 강수일수' .. _if,
	annual_mode = 'sum',
	WANTROW = _ifany(' rain days'),
	mode = 'basic',
	group_name = 'rain days',
	color_scheme = _ifset,
	date_mode = true,
	scale_factor = '1',
	label = '평균 강우일수' .. _if,
	annual_mode = 'sum',
	WANTROW = _ifany(' snow days'),
	mode = 'basic',
	group_name = 'snow days',
	color_scheme = _ifset,
	date_mode = true,
	scale_factor = '1',
	label = '평균 강설일수' .. _if,
	annual_mode = 'sum',
	WANTROW = _ifany(' humidity'),
	mode = 'basic',
	group_name = 'humidity',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '평균 상대 습도 (%)' ..
		_if ..
		_if,
	annual_mode = 'avg',
	WANTROW = _ifany(' afthumidity'),
	mode = 'basic',
	group_name = 'afthumidity',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '평균 오후 상대 습도 (%)' ..
		_if ..
		_if,
	annual_mode = 'avg',
	WANTROW = _ifany(' dew point C') or _ifany(' dew point F'),
	mode = 'temperature',
	group_name = 'dew point',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '평균 이슬점 °' .. _if .. _if('single line', ' (°' .. _if .. ')'),
	annual_mode = 'avg',
	WANTROW = not _ifset('single line') and (_ifany(' dew point C') or _ifany(' dew point F')),
	mode = 'temperature',
	group_name = 'dew point',
	second_line = true,
	color_scheme = _ifset,
	scale_factor = '1',
	label = '평균 이슬점 °' .. _if,
	show = _if,
	annual_mode = 'avg',
	WANTROW = _ifany(' sun'),
	mode = 'basic',
	group_name = 'sun',
	color_scheme = _ifset,
	date_mode = true,
	scale_factor = '1',
	label = '평균 월간 일조시간',
	annual_mode = 'sum',
	WANTROW = _ifany('d sun'),
	mode = 'basic',
	group_name = 'd sun',
	color_scheme = _ifset,
	include_space = false,
	scale_factor = '30.44',
	label = '평균 일일 일조시간',
	annual_mode = 'avg',
	WANTROW = _ifany(' light'),
	mode = 'basic',
	group_name = ' light',
	color_scheme = _ifset,
	include_space = false,
	scale_factor = '30.44',
	label = '평균 일일 낮 시간',
	annual_mode = 'avg',
	WANTROW = _ifany(' percentsun'),
	mode = 'basic',
	group_name = 'percentsun',
	color_scheme = _ifset,
	scale_factor = '7.2',
	label = '가능 일조율',
	annual_mode = 'avg',
	WANTROW = _ifany(' uv'),
	mode = 'basic',
	group_name = 'uv',
	color_scheme = _ifset,
	scale_factor = '1',
	label = '평균 자외선 지수',
	annual_mode = 'avg',
makeSources,
end

local function makeFrame
	-- Kludge to pass arguments for a single row to buildRow.
	-- Later: Refactor buildRow so this is not needed.
	return {
		args = self_args,
		getParent = function (self) return makeFrame end,
end

local function main(frame)
	local buildRow = require('Module:Weather box/row').buildRow
	local args = frame:getParent.args
	local results = {}
	for i, def in ipairs(getDefinitions) do
		local row
		if type(def) == 'string' then
			row = def
		elseif def.WANTROW then
			row = buildRow(makeFrame)
		else
			row = ''
		end
		results[i] = row
	end
	return '' -- prevent Scribunto from inserting a blank line before the table
end

return {
	main = main,