local z = {}
local lua_error = error
local error = require( 'Module:Error' )

local function makeText( frame, v )
	local text = v.text
	if not v.preprocessed then
		text = frame:preprocess( text )
	end
	return mw.text.trim( text ) .. '\n'
end

local function makeItem( frame, v )
	local text = '* '
	if v.original then
		text = text .. '原文:' .. v.original .. ';'
	end
	return text .. '-{D|' .. v.rule .. '}-当前显示为:-{|' .. v.rule .. '}-\n'
end

function z.checkError(frame)
	local name = frame.args[1]
	if not name or name == '' then
		return ''
	end
	local require_success, data = pcall(require, 'Module:CGroup/' .. name )
	local body = ''
	if not require_success then
		local error_message = tostring(data)
		if (({mw.ustring.find(error_message, "module .+ not found")})[1] and 
				mw.ustring.lower(tostring(name)) == mw.ustring.lower(tostring(({mw.ustring.match(error_message, "module ['\"]Module:CGroup[\\/](.+)['\"] not found" )})[1])))
			or ({mw.ustring.find(error_message, "loop or previous")})[1] then
				local working_frame = (frame or {}).preprocess and frame or mw.getCurrentFrame()
				--指向自己本身或循環的重定向自動提交速刪
				body = body .. working_frame:preprocess("{{delete|r5}}") 
		else
			body = body .. error.error{ '讀取转换组模块“' .. name .. '”發生錯誤。' }
			body = body .. '[[Category:有错误的公共转换组模块|' .. name .. ']]\n'
			body = body .. ':請檢查:\n'
			body = body .. ':*轉換組頁面是否存在\n'
			body = body .. ':*轉換組語法是否有錯誤\n'
			body = body .. ":'''錯誤訊息如下:'''\n::"
		end
	end
	return body
end

function z.main( frame )
	local name = frame.args[1]
	--令除錯主控台可以運行
	local working_frame = (type((frame or {}).preprocess)==type(tonumber)) and frame or mw.getCurrentFrame()
	if not name or name == '' then
		return ''
	end
	local require_success, data = pcall(require, 'Module:CGroup/' .. name )
	if not require_success then
		local error_message = tostring(data)
		--指向自己本身或循環的重定向
		if (({mw.ustring.find(error_message, "module .+ not found")})[1] and 
				mw.ustring.lower(tostring(name)) == mw.ustring.lower(tostring(({mw.ustring.match(error_message, "module ['\"]Module:CGroup[\\/](.+)['\"] not found" )})[1])))
			or ({mw.ustring.find(error_message, "loop or previous")})[1] then
				local cgroup_name = ({mw.ustring.match(error_message, "['\"]Module:CGroup[\\/](.+)['\"]" )})[1]
				return working_frame:expandTemplate{ title = 'Template:CGroup redirect', args = { 'Module:CGroup/' .. (cgroup_name or name) } }
		elseif ({mw.ustring.find(error_message, "module .+ not found")})[1] then
			local cgroup_name = ({mw.ustring.match(error_message, "['\"]Module:CGroup[\\/](.+)['\"]" )})[1]
			return error.error{ '找不到名稱為“[[Module:CGroup/' .. cgroup_name ..'|' .. cgroup_name .. ']]”的转换组模块。\n' }
		else
			return lua_error(data,0)
		end
	end
	if type( data ) ~= 'table' or not data.name or data.name == '' then
		return error.error{ '指定模块“' .. name .. '”不是有效的转换组' }
	end
	if data.name ~= name then
		return working_frame:expandTemplate{ title = 'Template:CGroup redirect', args = { 'Module:CGroup/' .. data.name } }
	end
	local pieces = {
        working_frame:preprocess{ text = '__NOEDITSECTION__'},
		working_frame:expandTemplate{ title = 'Template:Bot use warning', args = { bots = '[[User:cewbot/log/20191129/configuration]]' } },
		'<strong>以下為[[Wikipedia:字詞轉換處理/公共轉換組|公共转换组]]Module:CGroup/' .. data.name .. '的內容。\n描述:' .. data.description .. '</strong>\n',
	}
	for i, v in ipairs( data.content ) do
		if v.type == 'text' then
			table.insert( pieces, makeText( working_frame, v ) )
		elseif v.type == 'item' then
			table.insert( pieces, makeItem( working_frame, v ) )
		end
	end
	table.insert( pieces, '[[Category:公共转换组模块|' .. name .. ']]' )
	return table.concat( pieces )
end

function z.dialog( frame )
	local name = frame.args[1]
	if not name or name == '' then
		return ''
	end
	local data = require( 'Module:CGroup/' .. name )
	local pieces = { '<div class="mw-collapsible mw-collapsed"><span class="plainlinks" style="float: right;">&#91;[',
		tostring( mw.uri.fullUrl( 'Module:CGroup/' .. name, { action = 'edit' } ) ), ' 编辑]&#93;</span>\n',
		'; 本文使用[[Wikipedia:字詞轉換處理/公共轉換組|公共转换组]]“' .. data.description .. '”。\n',
		'<div class="mw-collapsible-content">\n' }
	for i, v in ipairs( data.content ) do
		if v.type == 'item' then
			table.insert( pieces, makeItem( frame, v ) )
		end
	end
	table.insert( pieces, '</div></div>' )
	return table.concat( pieces )
end

function z.json( frame )
	local name = frame.args[1]
	if not name or name == '' then
		return 'null'
	end
	local data = require( 'Module:CGroup/' .. name )
	local json = require( 'Module:MicroJSON' )
	return json.encode_object( data, {
		name = '',
		description = '',
		content = {
			{ type = '', [true] = '' },
		},
	} )
end

return z