local cfg = mw.loadData('Module:Sidebar/configuration')

local p = {}

local getArgs = require('Module:Arguments').getArgs

--
i18n conversion
공통 

local param_ko_common = {
	['기본모양'] = 'basestyle', -- 본래 틀에 없던 항목
	['윗제목모양'] = 'abovestyle',
	['아랫글모양'] = 'belowstyle',
	['안내바모양'] = 'navbarstyle',
	['안내바'] = 'navbar',
	['이름'] = 'name',
	-- [''] = 'tnavbarstyle', -- 본래 틀에 없던 항목

--
i18n conversion
p.sidebar 전용

local param_ko_sidebar = {
	['자식'] = 'child',
	--[''] = 'wraplinks',
	['전체속성'] = 'bodyclass',
	['속성'] = 'class',
	--[''] = 'float',
	['너비'] = 'width',
	['전체모양'] = 'bodystyle',
	['모양'] = 'style',
	['제목'] = 'title',
	['큰제목'] = 'outertitle',
	['큰제목속성'] = 'outertitleclass',
	['큰제목모양'] = 'outertitlestyle',
	['윗그림'] = 'topimage',
	['윗그림속성'] = 'topimageclass',
	['윗그림모양'] = 'topimagestyle',
	['윗그림설명'] = 'topcaption',
	['윗그림설명모양'] = 'topcaptionstyle',
	['앞제목'] = 'pretitle',
	['앞제목속성'] = 'pretitleclass',
	['앞제목모양'] = 'pretitlestyle',
	['제목속성'] = 'titleclass',
	['제목모양'] = 'titlestyle',
	['그림'] = 'image',
	['그림속성'] = 'imageclass',
	['그림모양'] = 'imagestyle',
	['그림설명'] = 'caption',
	['그림설명모양'] = 'captionstyle',
	['윗제목'] = 'above',
	['윗제목속성'] = 'aboveclass',
	['묶음속성'] = 'headingclass',
	['묶음모양'] = 'headingstyle',
	['내용속성'] = 'contentclass',
	['내용모양'] = 'contentstyle',
	['아랫글'] = 'below',
	['아랫글속성'] = 'belowclass',
	--[''] = 'tnavbar',
	--[''] = 'navbarfontstyle',
	--[''] = 'tnavbarfontstyle',

--
i18n conversion
p.collapsible 전용

local param_ko_collapsible = {
	['확장'] = 'expanded',
	['목록틀모양'] = 'listframestyle',
	['목록제목속성'] = 'listtitleclass',
	['목록제목모양'] = 'listtitlestyle',
	['목록속성'] = 'listclass',
	['목록모양'] = 'liststyle'

--
i18n conversion
보조 함수

local function localname
	return koArgs[parameter] or parameter
end

--
i18n conversion
주 함수

local function i18nConv
	local tmpLocalArgs = {}
	for k, v in pairs(localArgs) do
		if v ~= '' then
			tmpLocalArgs[localname] = v
		end
	end
	return tmpLocalArgs
end

--
Categorizes calling templates and modules with a 'style' parameter of any sort
for tracking to convert to TemplateStyles.

TODO after a long cleanup: Catch sidebars in other namespaces than Template and Module.
TODO would probably want to remove /log and /archive as CS1 does

local function categorizeTemplatesWithInlineStyles(args)
	local title = mw.title.getCurrentTitle
	if title.namespace ~= 10 and title.namespace ~= 828 then return '' end
	for _, pattern in ipairs (cfg.i18n.pattern.uncategorized_conversion_titles) do
		if title.text:match(pattern) then return '' end
	end
	
	for key, _ in pairs(args) do
		if mw.ustring.find or key == 'width' then
			return cfg.i18n.category.conversion
		end
	end
end

--
For compatibility with the original 
implementation, which passed some parameters through to trim their
whitespace. This also triggered the automatic newline behavior.

-- See (meta:Help:Newlines and spaces#Automatic newline)
local function trimAndAddAutomaticNewline(s)
	s = mw.ustring.gsub(s, "^%s*(.-)%s*$", "%1")
	if mw.ustring.find or mw.ustring.find then
		return '\n' .. s
	else
		return s
	end
end

--
Finds whether a sidebar has a subgroup sidebar.

local function hasSubgroup(s)
	if mw.ustring.find then
		return true
	else
		return false
	end
end

local function has_navbar
	return navbar_mode ~= cfg.i18n.navbar_none and
		navbar_mode ~= cfg.i18n.navbar_off and
		(
			sidebar_name or
			mw.getCurrentFrame:getParent:getTitle:gsub ~=
			cfg.i18n.title_not_to_add_navbar
		)
end

local function has_list_class
	local patterns = {
		'^' .. htmlclass .. '$',
		'%s' .. htmlclass .. '$',
		'^' .. htmlclass .. '%s',
		'%s' .. htmlclass .. '%s'
	
	for arg, value in pairs(args) do
		if type(arg) == 'string' and mw.ustring.find then
			for _, pattern in ipairs(patterns) do
				if mw.ustring.find then
					return true
				end
			end
		end
	end
	return false
end

-- there are a lot of list classes in the wild, so we add their TemplateStyles
local function add_list_styles(args)
	local frame = mw.getCurrentFrame
	local function add_list_templatestyles
		if has_list_class then
			return frame:extensionTag{
				name = 'templatestyles', args = { src = templatestyles }
		else
			return ''
		end
	end
	
	local plainlist_styles = add_list_templatestyles
	local hlist_styles = add_list_templatestyles
	
	-- a second workaround for phab:T303378
	-- when that issue is fixed, we can actually use has_navbar not to emit the
	-- tag here if we want
	if has_navbar and hlist_styles == '' then
		hlist_styles = frame:extensionTag{
			name = 'templatestyles', args = { src = cfg.i18n.hlist_templatestyles}
	end

	-- hlist -> plainlist is best-effort to preserve old Common.css ordering. [hlist_note]
	return hlist_styles .. plainlist_styles
end

-- work around phab:T303378
-- for each arg: find all the templatestyles strip markers, insert them into a
-- table. then remove all templatestyles markers from the arg
local function move_hiding_templatestyles(args)
	local gfind = string.gfind
	local gsub = string.gsub
	local templatestyles_markers = {}
	local strip_marker_pattern = '(\127[^\127]*UNIQ%-%-templatestyles%-%x+%-QINU[^\127]*\127)'
	for k, arg in pairs(args) do
		for marker in gfind do
			table.insert
		end
		args[k] = gsub
	end
	return templatestyles_markers
end

--
Main sidebar function. Takes the frame, args, and an optional collapsibleClass.
The collapsibleClass is and should be used only for sidebars with collapsible
lists, as in p.collapsible.

function p.sidebar
	if not args then
		args = getArgs(frame)
	end

	-- i18n conversion
	args = i18nConv
	args = i18nConv

	local hiding_templatestyles = table.concat(move_hiding_templatestyles(args))
	local root = mw.html.create
	local child = args.child and mw.text.trim(args.child) == cfg.i18n.child_yes

	root = root:tag('table')
	if not child then
		root 
			-- force collapsibleclass to be sidebar-collapse otherwise output nothing

		if args.outertitle then
			root
		end

		if args.topimage then
			local imageCell = root:tag('tr'):tag('td')

			imageCell

			if args.topcaption then
				imageCell
			end
		end

		if args.pretitle then
			root
							or cfg.i18n.class.pretitle)
		end
	else
		root
	end

	if args.title then
		if child then
			root
		else
			root
							or cfg.i18n.class.title)
		end
	end

	if args.image then
		local imageCell = root:tag('tr'):tag('td')

		imageCell

		if args.caption then
			imageCell
		end
	end

	if args.above then
		root
	end

	local rowNums = {}
	for k, v in pairs(args) do
		k = '' .. k
		local num = k:match('^heading(%d+)$') or k:match('^content(%d+)$') or k:match('^묶음(%d+)$') or k:match('^내용(%d+)$')
		if num then table.insert(rowNums, tonumber(num)) end
	end
	table.sort(rowNums)
	-- remove duplicates from the list (e.g. 3 will be duplicated if both heading3
	-- and content3 are specified)
	for i = #rowNums, 1, -1 do
		if rowNums[i] == rowNums[i - 1] then
			table.remove
		end
	end

	for i, num in ipairs(rowNums) do
		local heading = args['heading' .. num] or args['묶음' .. num]
		if heading then
			root
		end

		local content = args['content' .. num] or args['내용' .. num]
		if content then
			root
							or cfg.i18n.class.content)
					 -- Without a linebreak after the , a nested list like
					 -- "* " doesn't parse correctly.
		end
	end

	if args.below then
		root
	end

	if not child and has_navbar then
		root
						args.name,
						mini = 1,
						fontstyle = args.navbarfontstyle
	end
	
	local base_templatestyles = frame:extensionTag{
		name = 'templatestyles', args = { src = cfg.i18n.templatestyles }
	
	local templatestyles = ''
	if args['templatestyles'] and args['templatestyles'] ~= '' then
		templatestyles = frame:extensionTag{
			name = 'templatestyles', args = { src = args['templatestyles'] }
	end
	
	local child_templatestyles = ''
	if args['child templatestyles'] and args['child templatestyles'] ~= '' then
		child_templatestyles = frame:extensionTag{
			name = 'templatestyles', args = { src = args['child templatestyles'] }
	end
	
	local grandchild_templatestyles = ''
	if args['grandchild templatestyles'] and args['grandchild templatestyles'] ~= '' then
		grandchild_templatestyles = frame:extensionTag{
			name = 'templatestyles', args = { src = args['grandchild templatestyles'] }
	end

	return table.concat({
		add_list_styles(args), -- see [hlist_note] above about ordering
		base_templatestyles,
		templatestyles,
		child_templatestyles,
		grandchild_templatestyles,
		hiding_templatestyles,
		tostring(root),
		(child and cfg.i18n.category.child or ''),
		categorizeTemplatesWithInlineStyles(args)
end

local function list_title
	
	local title_text = trimAndAddAutomaticNewline(args['list' .. num .. 'title'] or args['목록' .. num .. '제목']
		or cfg.i18n.default_list_title)

	local title
	if is_centered_list_titles then
		-- collapsible can be finicky, so provide some CSS/HTML to support
		title = mw.html.create('div')
	else
		title = mw.html.create
	end
		
	local title_container = mw.html.create('div')
		-- don't /need/ a listnumtitleclass because you can do
		-- .templateclass .listnumclass .sidebar-list-title
	
	return title_container
end

--
Main entry point for sidebar with collapsible lists.
Does the work of creating the collapsible lists themselves and including them
into the args.

function p.collapsible(frame)
	local args = getArgs(frame)

	-- i18n conversion
	args = i18nConv
	args = i18nConv

	if not args.name and
		frame:getParent:getTitle:gsub ==
		cfg.i18n.collapse_title_not_to_add_navbar then
		args.navbar = cfg.i18n.navbar_none
	end

	local contentArgs = {}
	
	local is_centered_list_titles = false
	if args['centered list titles'] and args['centered list titles'] ~= '' then
		is_centered_list_titles = true
	end

	for k, v in pairs(args) do
		local num = string.match(k, '^list(%d+)$') or string.match(k, '^목록(%d+)$')
		if num then
			local expand = args.expanded and
				(args.expanded == 'all' or args.expanded == args['list' .. num .. 'name'] or args.expanded == args['목록' .. num .. '이름'])
			local row = mw.html.create('div')
			row
					-- don't /need/ a listnumstyleclass because you can do
					-- .templatename .listnumclass .sidebar-list

			contentArgs['content' .. num] = tostring(row)
		end
	end

	for k, v in pairs(contentArgs) do
		args[k] = v
	end

	return p.sidebar
end