local export = {}

local m_lang = require("Module:languages")

-- This module implements {{ko-etym-*}} (currently only {{ko-etym-native}}).

local refs = {
	{{"1", "hh"}, "''Hunminjeong'eum haerye'' ([[wikisource:ko:훈민정음#訓民正音解例|{{lang|ko|訓民正音解例 / 훈민정음해례}}]]), 1446", "okm"},
	{{"2", "he"}, "''Hunminjeong'eum eonhae'' ([[wikisource:ko:훈민정음언해|{{lang|ko|訓民正音諺解本 / 훈민정음언해본}}]]), 1446", "okm"},
	{{"3", "ss", "석보"}, "''Seokbo sangjeol'' ({{lang|ko|釋譜詳節 / 석보상절}}), 1447", "okm"},
	{{"4", "yb", "용가"}, "''Yongbi eocheon'ga'' ([[wikisource:ko:용비어천가|{{lang|ko|龍飛御天歌 / 용비어천가}}]]), 1447", "okm"},
	{{"5", "wc"}, "''Worin cheon'gangjigok'' ([[wikisource:ko:월인천강지곡|{{lang|ko|月印千江之曲 / 월인천강지곡}}]]), 1449", "okm"},
	{{"6", "sy"}, "''Seonjong yeonggajip eonhae'' ({{lang|ko|禪宗永嘉集諺解 / 선종영가집언해}}), 1456", "okm"},
	{{"7", "ws", "wi", "월석"}, "''Worin seokbo'' ({{lang|ko|月印釋譜 / 월인석보}}), 1459", "okm"},
	{{"8", "ne"}, "''Neung'eomgyeong eonhae'' ({{lang|ko|楞嚴經諺解 / 능엄경언해}}), 1461", "okm"},
	{{"9", "mb"}, "''Myobeomnyeonhwagyeong eonhae'' ({{lang|ko|妙法蓮華經諺解 / 묘법연화경언해}}), 1463", "okm"},
	{{"10", "wg"}, "''Won'gakgyeong eonhae'' ({{lang|ko|圓覺經諺解 / 원각경언해}}), 1465", "okm"},
	{{"11", "be"}, "''Beobeo eonhae'' ({{lang|ko|法語諺解 / 법어언해}}), 1466", "okm"},
	{{"12", "nh"}, "''Eoje naehun'', ({{lang|ko|御製內訓 / 어제내훈}}), 1475 ", "okm"},
	{{"13", "gg"}, "''Gugeupbang eonhae'' ({{lang|ko|救急方諺解 / 구급방언해}}), 1466", "okm"},
	{{"14", "bdb"}, "''Bullyu dugongbu si eonhae'' ({{lang|ko|分類杜工部詩諺解 / 분류두공부시언해}}), 1481", "okm"},
	{{"15", "nm"}, "''Nammyeongjip eonhae'' ({{lang|ko|南明集諺解 / 남명집언해}}), 1482", "okm"},
	{{"16", "br"}, "''Baengnyeon chohae'' ({{lang|ko|百聯抄解 / 백련초해}}), mid-16th century", "okm"},
	{{"17", "bs"}, "''Beonyeok sohak'' ({{lang|ko|飜譯小學 / 번역소학}}), 1517", "okm"},
	{{"18", "bn"}, "''Beonyeok nogeoldae'' ({{lang|ko|飜譯老乞大 / 번역노걸대}}), 1517", "okm"},
	{{"19", "ir"}, "''Iryun haengsildo'' ({{lang|ko|二倫行實圖 / 이륜행실도}}), 1518 (Oksan Seowon ed.)", "okm"},
	{{"20", "hm"}, "''Hunmong jahoe'' ({{lang|ko|訓蒙字會 / 훈몽자회}}), 1527", "okm"},
	{{"21", "gh"}, "''Guhwang chwaryo'' ({{lang|ko|救荒撮要 / 구황촬요}}), 1554", "okm"},
	{{"22", "sj"}, "''Sinjeung yuhap'' ({{lang|ko|新增類合 / 신증유합}}), 1576", "okm"},
	{{"23", "se"}, "''Sohak eonhae'' ({{lang|ko|小學諺解 / 소학언해}}), 1586", "okm"},
	{{"24", "gci"}, "''Gyechuk ilgi'' ({{lang|ko|癸丑日記 / 계축일기}}), c. 1600 ", "ko-ear"},
	{{"25", "etj"}, "''Eonhae taesan jibyo'' ({{lang|ko|諺解胎産集要 / 언해태산집요}}), 1608", "ko-ear"},
	{{"26", "edj"}, "''Eonhae duchang jibyo'' ({{lang|ko|諺解痘瘡集要 / 언해두창집요}}), 1608", "ko-ear"},
	{{"27", "sge", "sgs"}, "''Seon'ga gwigam eonhae'' ({{lang|ko|禪家龜鑑諺解 / 선가귀감언해}}), 1610 (Songgwangsa ed.)", "ko-ear"},
	{{"28", "mg"}, "''Magyeong chojip eonhae'' ({{lang|ko|馬經抄集諺解 / 마경초집언해}}), 16th century", "ko-ear"},
	{{"29", "erh"}, "''Eorokhae'' ({{lang|ko|語錄解 / 어록해}}), 1652", "ko-ear"},
	{{"30", "sgg"}, "''Sin'gan guhwang chwaryo'' ({{lang|ko|新刊救荒撮要 / 신간구황촬요}}), 1660", "ko-ear"},
	{{"31", "pts"}, "''Bak Tongsa eonhae'' ({{lang|ko|朴通事諺解 / 박통사언해}}), 1677", "ko-ear"},
	{{"32", "yhy", "유해역"}, "''Yeogeo yuhae'' ({{lang|ko|譯語類解 / 역어유해}}), 1690", "ko-ear"},
	{{"33", "js"}, "''Jeongsok eonhae'' ({{lang|ko|正俗諺解 / 정속언해}} (of {{lang|ko|李源周敎授本 / 이원주 교수본}})), 1518", "okm"},
	{{"34", "ys"}, "''Sinjeonjachwi yeomchobang eonhae'' ({{lang|ko|新傳煮取焰硝方諺解 / 신전자취염초방언해}}), 1635", "ko-ear"},
	{{"35", "sg"}, "''Samgang haengsildo'' ({{lang|ko|三綱行實圖 / 삼강행실도}}), 1511", "okm"},
	{{"36", "boi"}, "''Bunmun onyeok ihaebang'' ({{lang|ko|分門瘟疫易解方 / 분문온역이해방}}), 1542", "okm"},
	{{"37", "yyb"}, "''Yeogeo yuhaebo'' ({{lang|ko|譯語類解補 / 역어유해보}}), 1775", "ko-ear"},
	{{"38", "ggg"}, "''Geumganggyeong samgahae'' ({{lang|ko|金剛經三家解 / 금강경삼가해}}), 1482", "okm"},
	{{"39", "du"}, "''Dong'ui bogam'' ({{lang|ko|東醫寶鑑 / 동의보감}}), 1613", "ko-ear"},
	{{"40", "bo"}, "''Byeogon sinbang'' ({{lang|ko|辟瘟新方 / 벽온신방}}), 1653", "ko-ear"},
	{{"41", "yhmb", "myb"}, "''Mong'eo yuhae bopyeon'' ({{lang|ko|蒙語類解補編 / 몽어유해보편}}), 1790", "ko-ear"},
	{{"42", "dssh"}, "''Dongguk sinsok samgang haengsildo'' ({{lang|ko|東國新續三綱行實圖 / 동국신속삼강행실도}}), 1617", "ko-ear"},
	{{"43", "ge"}, "''Gyeongminpyeon eonhae'' ({{lang|ko|警民編諺解 / 경민편언해}}), 1658", "ko-ear"},
	{{"44", "ggb"}, "''Gugeupganibang eonhae'' ({{lang|ko|救急簡易方諺解 / 구급간이방언해}}), 1489", "okm"},
	{{"45", "ag"}, "''Akhak gwebeom'' ({{lang|ko|樂學軌範 / 악학궤범}}), 1493", "okm"},
	{{"46", "bj"}, "''Bang'eon jipseok'' ({{lang|ko|方言集釋 / 방언집석}}), 1778", "ko-ear"},
	{{"47", "msg"}, "''Myeongseonggyeong eonhae'' ({{lang|ko|明聖經諺解 / 명성경언해}}), 1883", "ko-ear"},
	{{"48", "gy"}, "''Jīlín lèishì'' ({{lang|zh|鷄林類事}} / {{lang|ko|계림유사}}), 1103", "oko-lat"},
	{{"49", "ghw"}, "''Gukhan hoehwa'' ({{lang|ko|國韓會話 / 국한회화}}), 1895", "ko-ear"},
	{{"50", "mc"}, "''Magyeong chojip eonhae'' ({{lang|ko|馬經抄集諺解 / 마경초집언해}}), 1623~1649", "ko-ear"},
	{{"51", "nob"}, "''Nobakjimnam'' ({{lang|ko|老朴輯覽 / 노박집람}}), 1517", "okm"},
	{{"52", "cm"}, "''Cheophaemong'eo'' ({{lang|ko|捷解蒙語 / 첩해몽어}}), 1790", "ko-ear"},
	{{"53", "bb"}, "''Beonyeok Bak Tongsa'' ({{lang|ko|飜譯朴通事 / 번역박통사}}), before 1517", "okm"},
	{{"54", "sus"}, "''Samun seonghwi'' ({{lang|ko|三韻聲彙 / 삼운성휘}}), 1751", "ko-ear"},
	{{"55", "dy"}, "''Dongmun yuhae'' ({{lang|ko|同文類解 / 동문유해}}), 1748", "ko-ear"},
	{{"56", "ng"}, "''Nogyega'' ({{lang|ko|盧溪歌 / 노계가}}), 1636", "ko-ear"},
	{{"57", "jg"}, "''Joya gimun'' ({{lang|ko|朝野記聞 / 조야기문}}), 1684", "ko-ear"},
	{{"58", "ye"}, "''Yeosaseo eonhae'' ({{lang|ko|女四書諺解 / 여사서언해}}), 1736", "ko-ear"},
	{{"59", "jh"}, "''Joya hoetong'' ({{lang|ko|朝野會通 / 조야회통}}), 18th century", "ko-ear"},
	{{"60", "ij"}, "''Imhwa jeong'yeon'' ({{lang|ko|林花鄭延 / 임화정연}}), 18th century", "ko-ear"},
	{{"61", "jgw"}, "''Joseon gwannyeogeo '' ({{lang|ko|朝鮮館驛語 / 조선관역어}}), 1403~1424", "okm"},
	{{"62", "sc"}, "''Seokbong cheonjamun'' ({{lang|ko|石峰千字文 / 석봉천자문}}), 1583", "okm"},
	{{"63", "ns"}, "''Namsarok'' ({{lang|ko|南槎錄 / 남사록}}), 1601", "ko-ear"},
	{{"64", "tj"}, "''Tamnaji'' ({{lang|ko|眈羅志 / 탐라지}}), 1653", "ko-ear"},
	{{"65", "me"}, "''Maengja eonhae'' ({{lang|ko|孟子諺解 / 맹자언해}}), 1590", "okm"},
	{{"66", "gre"}, "''Garye eonhae'' ({{lang|ko|家禮諺解 / 가례언해}}), 1632", "ko-ear"},
	{{"67", "tsg"}, "''Taesang gameungpyeondoseol eonhae'' ({{lang|ko|太上感應篇圖說諺解 / 태상감응편도설언해}}), 1852", "ko-ear"},
	{{"68", "chi"}, "''Childae manbeop'' ({{lang|ko|七大萬法 / 칠대만법}}), 1569", "okm"},
	{{"69", "gcj"}, "''Gwangju cheonjamun'' ({{lang|ko|光州千字文 / 광주천자문}}), 1575", "okm"},
	{{"70", "hyg"}, "''Hyang'yak gugeupbang'' ({{lang|ko|鄕藥救急方 / 향약구급방}}), 1236", "oko-lat"},
	{{"71", "ny"}, "''Eonhae nabyak jeungchibang'' ({{lang|ko|諺解臘藥症治方 / 언해납약증치방}}), 17th century", "ko-ear"},
	{{"72", "csg"}, "''Cheonui sogam'' ({{lang|ko|闡義昭鑑 / 천의소감}}), 1756", "ko-ear"},
	{{"73", "gge"}, "''Geumganggyeong eonhae'' ({{lang|ko|金剛經諺解 / 금강경언해}}), 1464", "okm"},
	{{"74", "hb"}, "''Hanbul jajeon'' ({{lang|ko|韓佛字典 / 한불자전}}), 1880", "ko-ear"},
	{{"75", "bdbj"}, "''Bullyu dugongbu si eonhae junggan'' ({{lang|ko|分類杜工部詩諺解重刊本 / 분류두공부시언해중간본}}), 1632", "ko-ear"},
	{{"76", "ms"}, "''Mongsanhwasang beobeo yangnok eonhae'' ({{lang|ko|蒙山和尙法語略錄諺解 / 몽산화상법어약록언해}}), 1459~1467", "okm"},
	{{"77", "yhm", "my"}, "''Mong'eo yuhae'' ({{lang|ko|蒙語類解 / 몽어유해}}), 1768", "ko-ear"},
	{{"78", "yj"}, "''Seonggwanjajaegusuyukja seonjeong eonhae'' ({{lang|ko|聖觀自在求修六字禪定諺解 / 성관자재구수육자선정언해}}), 1560", "okm"},
	{{"79", "gj"}, "''Gwang jaemulbo'' ({{lang|ko|廣才物譜 / 광재물보}}), 19th century", "ko-ear"},
	{{"80", "sbe"}, "''Sabeobeo eonhae'' ({{lang|ko|四法語諺解 / 사법어언해}}), 1467", "okm"},
}

local ref_table = {}

for _, ref in ipairs(refs) do
	local keys, text, langcode = unpack(ref)
	for _, key in ipairs(keys) do
		ref_table[key] = {text, langcode}
	end
end

-- Implementation of {{ko-etym-native}}.
-- [[The shorthand parameter for first attestations will be deprecated soon in favor of creating actual entries or
-- citation pages for Middle Korean. See discussion at [[Wiktionary:Beer parlour/2019/September#First attestations
-- in the etymology section]]. --May not be accurate any more. ([[User:Benwing2]], 2023-09-04)
function export.ko_etym_native(frame)
	local params = {
		[1] = {},
		["also"] = {type = "boolean"},
		[2] = {alias_of = "form"},
		["form"] = {},
		[3] = {alias_of = "yale"},
		["yale"] = {},
		[4] = {alias_of = "year"},
		["year"] = {},
		["hangul"] = {type = "boolean"},
		["dot"] = {default = "."},
		["nodot"] = {type = "boolean"},
		["nocat"] = {type = "boolean"},
		["nocap"] = {type = "boolean"},
	}
		
	local parargs = frame:getParent().args
	if parargs["dot"] == "" then
		require("Module:debug").track("ko-etym/ko-etym-native/empty-dot")
	end
	local args = require("Module:parameters").process(parargs, params)

	local parts = {}
	local categories = {}

	if not args[1] then
		table.insert(parts, "Of native Korean origin")
	else
		local text, langcode
		if ref_table[args[1]] then
			text, langcode = unpack(ref_table[args[1]])
			text = text:gsub("{{lang|([a-z]+)|(.-)}}", function(langtextcode, langtext)
				local lang = m_lang.getByCode(langtextcode, true)
				return require("Module:script utilities").tag_text(langtext, lang)
			end)
		else
			if not args.year then
				error("1='" .. args[1] .. "' is not a known reference work, so year= must be supplied")
			end
			text = args[1] .. ", " .. args.year
			if args.year:find("^[0-9]+$") then
				if tonumber(args.year) < 1300 then
					langcode = "oko-lat"
				elseif tonumber(args.year) < 1598 then
					langcode = "okm"
				else
					langcode = "ko-ear"
				end
			else
				langcode = "okm"
			end
		end
		local first
		if args.also then
			first = "Also"
		else
			first = "First"
		end
		if args.hangul then
			table.insert(parts, "In the [[Hangul]] script, ")
			table.insert(parts, mw.getContentLanguage():lcfirst(first))
		else
			table.insert(parts, first)
		end
		table.insert(parts, " attested in the ")
		table.insert(parts, text)

		if args.form then
			table.insert(parts, ", as ")
			table.insert(parts, require("Module:etymology").format_inherited(m_lang.getByCode("ko"),
				{lang = m_lang.getByCode(langcode, true, "allow etym"),
				term = args.form,
				tr = "-",
				}))
			if args.yale then
				table.insert(parts, "&nbsp;([[w:Yale romanization of Korean|Yale]]: ''")
				table.insert(parts, args.yale)
				table.insert(parts, "'')")
			end
		end
	end

	if not args.nodot then
		table.insert(parts, args.dot)
	end

	if not args.nocat then
		table.insert(categories, "Native Korean words")
	end

	local parts_concat = table.concat(parts)
	if args.nocap then
		parts_concat = mw.getContentLanguage():lcfirst(parts_concat)
	end
	
	return parts_concat .. require("Module:utilities").format_categories(categories, m_lang.getByCode("ko"))
end

return export