local mTableTools = require('Module:TableTools')
local mSideBox = require('Module:Side box')
local lang = mw.language.new('en')

local p = {}

local function formatLength(length)
	-- Formats a duration in seconds in "(h:)mm:ss" (minutes are zero-padded
	-- only if there are hours).
	if not length or length == 0 then
		return nil
	end

	-- Add 0.5 to offset the rounding down
	local t = lang:getDurationIntervals
	local s = t.seconds and string.format or '00'
	local m = t.minutes or 0

	local span = mw.html.create('span'):addClass('duration')
	if t.hours then
		span
		m = string.format
	end
	span
	return tostring(span)
end

local function renderRow
	-- Renders the HTML for one file description row.
	if not filename then
		return nil
	end

	length = formatLength(length)
	length = length and string.format(' (%s)', length) or ''

	local root = mw.html.create('')
	root:tag('div')
				'%s%s',
				filename,
				title or '',
				length
			))
					file = filename,
					size = hasImage and '232px' or '215px',
					alt = alt,
					start = start
				or nil
			)
	return tostring(root)
end

local function renderTrackingCategories
	-- Renders all tracking categories produced by the template.
	-- isPlain, hasMissing and isEmpty are passed through from p._main,
	-- and the titleObj is only used for testing purposes.
	local cats = {}
	local currentTitle = titleObj or mw.title.getCurrentTitle
	if currentTitle.namespace == 0 then
		-- We are in mainspace.
		if not isEmpty then
			cats[#cats + 1] = 'hAudio 마이크로포맷을 사용하는 문서'
		end
		if hasMissing then
			cats[#cats + 1] = '비어있는 듣기 틀을 사용하는 문서'
		end
	end
	if isPlain then
		cats[#cats + 1] = 'plain 변수를 사용하는 듣기 틀'
	end
	for i, cat in ipairs(cats) do
		cats[i] = string.format
	end
	return table.concat(cats)
end

function p._main(args)
	-- Organise the arguments by number.
	local isPlain = (args.plain or args["간단"]) == 'yes'
	local isEmbedded = args.embed and true
	local hasImage = not isPlain and not isEmbedded and (args.image or args["그림"]) ~= 'none'

	local numArgs, missingFiles = {}, {}
	do
		local origNumArgs = mTableTools.numData(args)
		origNumArgs[1] = origNumArgs.other -- Overwrite args.filename1 etc. with args.filename etc.
		origNumArgs = mTableTools.compressSparseArray(origNumArgs)
		for i, t in ipairs(origNumArgs) do
			-- Check if the files exist.
			local obj = (t.filename or t["파일이름"] or t["파일 이름"]) and mw.title.makeTitle(-2, (t.filename or t["파일이름"] or t["파일 이름"]))
			if obj and obj.exists then
				if (t.length or t["길이"]) == 'yes' or
					-- Show length if the video height would be less than 150px
					obj.file.width / obj.file.height > (hasImage and 1.547 or 1.434)
				then
					t.length = obj.file.length
				else
					t.length = nil
				end
				numArgs[#numArgs + 1] = t
			else
				missingFiles[#missingFiles + 1] = (t.filename or t["파일이름"] or t["파일 이름"]) or i
			end
		end
	end

	-- Render warning
	local hasMissing = #missingFiles ~= 0
	local previewWarning = ''
	if hasMissing then
		for i, v in ipairs(missingFiles) do
			missingFiles[i] = type(v) == 'string'
				and string.format
				or string.format
		end
		previewWarning = string.format(
			'%s을 포함하는 틀:듣기를 사용하는 문서',
			mw.text.listToText(missingFiles)
		)
		previewWarning = require('Module:If preview')._warning({previewWarning})
	end

	-- Exit early if none exist.
	if #numArgs == 0 then
		return previewWarning .. renderTrackingCategories
	end

	-- Build the arguments for 
	local sbArgs = {
		metadata = 'no',
		position = (isPlain or isEmbedded) and 'left' or (args.pos or args["위치"]),
		style = (args.style or args["모양"]),
		templatestyles = 'Module:Listen/styles.css'

	-- Class arguments
	do
		local class = {
			'listen',
			'noprint'
		if isPlain then
			table.insert
		end
		if isEmbedded then
			table.insert
		end
		if not hasImage then
			table.insert
		end
		if (args.pos or args["위치"]) == 'left' and not isPlain and not isEmbedded then
			table.insert
		elseif (args.pos or args["위치"]) == 'center' then
			table.insert
		end

		sbArgs.class = table.concat
	end

	-- Image
	if not isPlain and not isEmbedded then
		if (args.image or args["그림"]) then
			sbArgs.image = (args.image or args["그림"])
		else
			local images = {
				["소리"] = 'Audio-input-microphone.svg',
				speech = 'Audio-input-microphone.svg',
				["음악"] = 'Gnome-mime-audio-openclipart.svg',
				music = 'Gnome-mime-audio-openclipart.svg',
				default = 'Gnome-mime-sound-openclipart.svg'
			sbArgs.image = mFileLink._main{
				file = (args.type or args["유형"]) and images[(args.type or args["유형"])] or images.default,
				size = '65x50px',
				location = 'center',
				link = '',
				alt = ''
		end
	end

	-- Text
	do
		local header
		if (args.header or args["윗글"]) then
			header = mw.html.create('div')
			header:addClass('listen-header')
			header = tostring(header) .. '\n'
		else
			header = ''
		end
		local text = {}
		for i, t in ipairs(numArgs) do
			text[#text + 1] = renderRow(
				(t.filename or t["파일이름"] or t["파일 이름"]), (t.title or t["제목"]), (t.play or t["재생"]), t.alt, (t.description or t["설명"]), (t.start or t["시작"]),
				(t.length or t["길이"]), hasImage
			)
			if numArgs[i + 1] then
				text[#text + 1] = ''
			end
		end
		sbArgs.text = header .. table.concat(text)
	end

	-- Below
	if not isPlain and not isEmbedded and (args.help or args["도움말"]) ~= 'no' then
		sbArgs.below = string.format
	end

	-- Render the side box.
	local sideBox = mSideBox._main(sbArgs)

	-- Render the tracking categories.
	local trackingCategories = renderTrackingCategories

	return previewWarning .. sideBox .. trackingCategories
end

function p.main(frame)
	local origArgs = frame:getParent.args
	local args = {}
	for k, v in pairs(origArgs) do
		if v ~= '' then
			args[k] = v
		end
	end
	return p._main(args)
end