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">The license "' .. template_name ..  '" does not exist.</span>' ..
					'[[Category:Wikipedia dual licensed files with invalid licenses]]'
			)
		}
	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, the copyright holder of this work,\'\'\' hereby publish%s, it under the following license%s:\'\'',
		args['author'] or 'I',
		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:Files licensed by third parties|%s]]', currentTitle.fullText)
	else
		return mw.ustring.format('[[Category:Self-published work|%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 class="center">%s</div>%s</div>%s'
	local initial_text = p.start_line(args)
	local final_line = p.more_than_one(args) and "<div class='center'>''You may select the license of your choice.''</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 '<br>' .. tstyles .. mw.ustring.format(fmt_string_tmpl, initial_text, templates, final_line, categories) .. errors
end

return p
-- </nowiki>