local p = {}

--[=[TODO:
	use mw.html since it exists
]=]

local _ppoem = require("Module:Ppoem")._ppoem
local getArgs = require("Module:Arguments").getArgs

function p._tpp(args)
	local res = ""
	-- if not args.text and not args[2] then args[1] is assumed to be the text, but args.title will always be the title.
	args.text = args.text or args[2]
	local notitle = false
	local notext = false
	if not args.text then
		notitle = true
		args.text = args[1]
	end
	if not args.text then
		notext = true
	end
	if not notitle then
		args.title = args.title or args[1]
	end
	args["end"] = args["end"] or args.e
	args.start = args.start or args.st -- s used to be taken
	args.quote = args.quote or args.q
	if args.title and args.title ~= "" then
		res = res .. '<div class="wst-center tiInherit ws-poem-tpp-title" style="margin-bottom:1em">' .. args.title .. '</div>'
	end
	if args.quote then
		res = res ..'<div style="margin-bottom:1em">' .. _ppoem({args.quote}) .. '</div>'
	end
	if args.text then
		if args.quote then
			local i, j
			i, j = mw.ustring.find(args.text, '^[ \n\t]*<div class="wst%-dhr[^<]->&nbsp;</div>', 0) --dhr
			if not j then
				i, j = mw.ustring.find(args.text, '^[ \n\t]*<span class="wst%-dhr[^<]->&nbsp;</span>', 0) --dhri
			end
			if j then
				args.text = mw.ustring.sub(args.text, j+1, #args.text) -- I manually added dhrs after quotes, removing them for backwards compatibility
			end
		end
		local newArgs = {}
		for k, v in pairs(args) do
			if k == "text" or k == "title" or k == 1  or k == "quote" or k == "q" or k == "e" or k == "s" or k == "size" or k == "st" or k == 2 or k == "start" or k == "end" then
				-- do nothing
			else
				newArgs[k] = v -- pass on every other parameter (ppoem's got a lot of them)
			end
		end
		local poems = mw.text.split(args.text, ">><<\n", true)
		for k, v in pairs(poems) do
			local t = mw.text.split(v, "\n", true)
			for a, b in pairs(t) do
				if string.sub(b, 0, 2) == "^>" and a > 1 then
					t[a] = '<span style="visibility:hidden">' .. t[a-2] .. '</span>' .. string.sub(b, 3, #b)
				end
				local i, j = mw.ustring.find(b, '^;+', 0)
				if j then
					t[a] = '<span style="margin-left:-' .. tostring(j) .. 'em">' ..  mw.ustring.sub(b, j+1, #b) .. "</span>"
				end
			end
			newArgs[1] = table.concat(t, "\n")
			if k == 1 then
				newArgs.start = args.start
			else
				newArgs.start = nil
			end
			if k == #poems then
				newArgs["end"] = args["end"]
			else
				newArgs["end"] = nil
			end
			res = res .. _ppoem(newArgs)
			if k ~= #poems then
				res = res .. '<div style="margin-bottom:1em"></div>'
			end
		end
	end

	return res
end

function p.tpp(frame)
	local args = getArgs(frame)
	return p._tpp(args)
end

return p