模組:Self

local p = {}

function p.decide_migration(args)
	if args['migration'] then
		return args['migration']
	end
	local licsense_migration_data = mw.loadJsonData( 'Module:Self/license_migration_data.json')
	for _, template_name in ipairs(args) do
		local migration_data = licsense_migration_data[string.lower(template_name)]
		if migration_data == 'redundant' then
			return migration_data
		end
	end
	return ''
end

function p.setup_template_params(template_name, frame,  args, migration)
	local title =  mw.title.new(template_name, 10)
	if not title.exists then
		return {
			txt='',
			errors=('<span class="error scribunto-error">「' .. template_name ..  '」授權條款不存在。</span>' ..
					'[[Category:包含無效授權條款的維基百科雙授權檔案]]'
			)
		}
	end

	return { txt=(frame:expandTemplate({
		title = template_name,
		args = {
			dw= (args['dw'] or 'no'),
			date= (args['date']  or ''),
			migration= (migration)
	 } })), errors='' }
end

function p.more_than_one(args)
	local c  = 0
	for _, __ in ipairs(args) do
		c = c + 1
		if c == 2 then
			return true
		end
	end
	return false
end

function p.start_line(args)
	local more_than_one = p.more_than_one(args)
	return mw.ustring.format(
		'\'\'\'%s,本作品的著作權持有者,決定用以下授權條款發佈本作品:\'\'\'',
		args['author'] or '我',
		args['author'] and 'es' or '',
		more_than_one and 's' or ''
	)
end

function p.categories(args)
	local currentTitle = mw.title.getCurrentTitle()
	local is_in_file_namespace = currentTitle.nsText == 'File'
	if not is_in_file_namespace then
		return ''
	end

	if args['author'] then
		return mw.ustring.format('[[Category:由第三方授權的檔案|%s]]', currentTitle.fullText)
	else
		return mw.ustring.format('[[Category:自發作品|%s]]', currentTitle.fullText)
	end
end

function p.main(frame)
	local args = frame:getParent().args
	local tstyles = frame:extensionTag( 'templatestyles', '', { src = 'Module:Self/styles.css' } )
	local fmt_string_tmpl = '<div class="wp-tmpl-self-license-wrapper">' ..
	'<div class="center">%s</div><div>%s</div>%s</div>%s'
	local initial_text = p.start_line(args)
	local final_line = p.more_than_one(args) and "<div class='center'>'''您可以選擇您想要的授權條款。'''</div>" or ''
	local categories = p.categories(args)
	local templates = ''
	local errors = ''
	local migration = p.decide_migration(args)
	for _, template_name in ipairs(args) do
		tmpl_with_args = p.setup_template_params(template_name, frame, args, migration)
		templates = templates .. tmpl_with_args.txt
		errors = errors .. tmpl_with_args.errors
	end
	return tstyles .. mw.ustring.format(fmt_string_tmpl, initial_text, templates, final_line, categories) .. errors
end

return p
-- </nowiki>