local m_string_utils = require("Module:string utilities")
local gsub = m_string_utils.gsub
local match = m_string_utils.match

local p = {}

local function check_pages(pages, format)
	for _, page in ipairs(pages) do
		if mw.title.new(page).exists then
			return string.format(format, page)
		end
	end
	return ""
end

local function parse_chinese_date(month_str, day_str)
	local month = match(month_str, "(%d+)月")
	local day = match(day_str, "(%d+)日")
	return tonumber(month), tonumber(day)
end

local function format_chinese_date(year, month, day, full)
	if full then
		return string.format("%d年/%d月%d日", year, month, day)
	else
		return string.format("%d月%d日", month, day)
	end
end

local function get_adjacent_date(year, month, day, offset, full)
	local date = os.time({year = year, month = month, day = day})
	local adj_date = os.date("*t", date + offset * 24 * 60 * 60)
	return format_chinese_date(adj_date.year, adj_date.month, adj_date.day, full)
end

function p.main(frame)
	local parent_args = frame:getParent().args

	local params = {
		[1] = {required = true, type = "string", default = "word"},
		[2] = {required = true, type = "string"},
		[3] = {required = true, type = "string"},
		[4] = {required = true, type = "string"},
		[5] = {required = true, type = "string"},
		[6] = {type = "string"},
		["audio"] = {type = "string"},
		["image"] = {type = "string"},
		["image_size"] = {type = "number", default = 150},
		["tr"] = {type = "string"}
	}

	local args = require("Module:parameters").process(parent_args, params)

	local word = args[1]
	local pos = args[2]
	local month_str = args[3]
	local day_str = args[4]
	local definition = args[5]
	local comment = args[6] or ""
	local audio = args["audio"]
	local image = args["image"]
	local image_size = args["image_size"]
	local tr = args["tr"] or ""

	local month, day = parse_chinese_date(month_str, day_str)
	local year = os.date("%Y")

	local audio_link = ""
	if audio and audio ~= "no" then
		audio_link = string.format('<div style="float:right">[[File:%s|noicon]]</div>', audio)
	else
		local audio_files = {
			"Zh-" .. word .. ".ogg"
		}
		audio_link = check_pages(audio_files, '<div style="float:right">[[%s|noicon]]</div>')
	end

	local current_title = mw.title.getCurrentTitle()
	local purge_url = current_title:fullUrl({action = 'purge'})
	
	local edit_template = frame:expandTemplate{title = "edit", args = {string.format("Wiktionary:每日一詞/%d年/%d月%d日", year, month, day)}}

	local header_row = mw.html.create('span')
	header_row:css('float', 'right')
		:css('font-size', 'small')
		:wikitext(edit_template .. ' · [' .. purge_url .. ' 刷新] · [[Wiktionary:每日一詞/' .. year .. '年/' .. month .. '月' .. day .. '日|檢視]]')

	local title_container = mw.html.create('div')
	title_container:css('display', 'flex')
		:css('justify-content', 'space-between')
		:css('align-items', 'center')
		:css('border-bottom', '1px solid #AAAAAA') -- underline
	
	-- skip h2 in the archive page
	if not string.find(mw.title.getCurrentTitle().fullText, "存檔") then
		local title_row = mw.html.create('h2')
		title_row:addClass('hp-segment-title')
			:css('margin-bottom', '0')
			:css('border-bottom', 'none') --  override underline in Mainpage.css
			:wikitext('[[Wiktionary:每日一詞|每日一詞]] <span style="font-size:small;">' .. format_chinese_date(year, month, day, false) .. '</span>')
		title_container:node(title_row)
	end
	
	-- always add header_row
	title_container:node(header_row)

	local output = mw.html.create('div')
		:addClass('mf-wotd')
		:attr('title', '每日一詞')
		:css('background-color', '#F9F9F0')
		:css('padding', '10px')

	local zh_l_template_args = {word}
	if tr ~= "" then
		zh_l_template_args["tr"] = gsub(tr, "(%d)([^<])", "<sup>%1</sup>%2")  -- 處理數字後不是 < 的情況
		zh_l_template_args["tr"] = gsub(zh_l_template_args["tr"], "^(%d)", "<sup>%1</sup>")  -- 處理開頭的數字
		zh_l_template_args["tr"] = gsub(zh_l_template_args["tr"], "(%d)<sub>", "<sup>%1</sup><sub>")  -- 處理數字後直接接 <sub> 的情況
	end
	local zh_l_template = frame:expandTemplate{title = 'zh-l', args = zh_l_template_args}

	local word_row = output:tag('div')
	word_row:css('padding-left', '10px')
		:wikitext(string.format("'''%s''' %s", zh_l_template, pos))

	if image and image ~= "" then
		local image_html = string.format('[[File:%s|%dpx|right]]', image, image_size)
		word_row:wikitext(image_html)
	end

	local def_row = output:tag('div')
	def_row:css('padding-left', '10px')
		:wikitext(string.format('<div id="WOTD-rss-description">\n%s</div>', definition))

	if comment ~= "" then
		def_row:tag('div')
			:css('padding-left', '10px')
			:wikitext(string.format('[[File:PointingHand.svg|20px]]&#32;<span style="font-size:80%;">%s</span>', comment))
	end

	if audio_link ~= "" then
		def_row:tag('div')
			:css('padding-left', '10px')
			:wikitext(audio_link)
	end

	local prev_day = get_adjacent_date(year, month, day, -1, true)
	local next_day = get_adjacent_date(year, month, day, 1, true)
	local target = match(word, 'span') and match(word, '%[%[(.-)#') or word

	local footer_row = output:tag('div')
	footer_row:css('font-size', '80%')
		:css('text-align', 'center')
		:css('vertical-align', 'top')
		:wikitext(string.format('[[Wiktionary:每日一詞/%s|← 昨日]] &#124; [[Wiktionary:每日一詞|關於每日一詞]] · [[Wiktionary:每日一詞#提名|提名新詞]] · <span class="plainlinks" title="Wiktionary:回饋">[https://zh.wiktionary.org/w/index.php?title=Wiktionary:回饋&action=edit&section=new&preload=Wiktionary:回饋%%2Fpreload&editintro=Wiktionary:回饋%%2Fintro&preloadtitle=每日一詞:&#91;&#91;%s&#93;&#93; 給予回饋]</span> &#124; [[Wiktionary:每日一詞/%s|明日&nbsp;→]]', 
			prev_day, mw.uri.encode(target), next_day
		))
	local container = mw.html.create('td')
	container:css('background-color', '#F9F9F0')
	container:node(title_container)
	container:node(output)

	return tostring(container)
end

return p