--[=[
Module description
]=]

local p = {} --p stands for package

local getArgs = require('Module:Arguments').getArgs
local yesno = require('Module:Yesno')
local make_style_string = require('Module:Optional style').make_style_string

--[=[
Get the appropriate text direction for a language
]=]
function p._text_direction(args)
	local rtl_langs = {
		ar = true, -- Arabic
		arc = true, -- Aramaic
		dv = true, -- Dhivehi
		fa = true, -- Persian
		ha = true, -- Hausa
		he = true, -- Hebrew
		hbo = true, -- Hebrew
		khw = true, -- Khowar
		ks = true, -- Kashmiri
		ku = true, -- Kurdish
		['obm-hebr'] = true, -- Moabite
		ps = true, -- Pashto
		syc = true, -- Syriac
		syr = true, -- Syriac
		ur = true, -- Urdu
		yi = true -- Yiddish
	}
	
	local lang = args.lang
	
	if lang and rtl_langs[lang] then
		return 'rtl'
	elseif type(lang) == 'string' then
		local stripped_lang = mw.text.split(lang, '-')[1]
		if rtl_langs[stripped_lang] then
			return 'rtl'
		end
	end
	
	return 'ltr'
end

function p.text_direction(frame)
	return p._text_direction(getArgs(frame))
end

local function make_attribute_string(attr, content)
	if attr and content then
		return attr .. '="' .. content .. '"'
	else
		return ''
	end
end

--[=[
Implements [[Template:Lang]] and [[Template:Lang block]]
]=]
function p._lang(args)
	local lang = args.language or args.lang or args[1] or "en"
	local text = args.text or args[2] or ""
	local inline = yesno(args.inline or "yes")
	
	local font = args.fonts or args.font
	local style = args.style
	
	local class = "wst-lang " .. (args.class or '')
	local attr = args.attr or ''
	
	local noclose = yesno(args.noclose or "no")
	
	--[=[
	Define the text direction
	]=]
	local dir = args.direction or args.dir or p._text_direction({['lang'] = lang})
	
	--[=[
	Span or div?
	]=]
	local tag
	if inline then
		tag = "span"
	else
		tag = "div"
	end
	
	--[=[
	Set the attributes.
	]=]
	local attr_table = {
		-- language
		make_attribute_string('lang', lang),
		make_attribute_string('xml:lang', lang),
		make_attribute_string('dir', dir),
		
		-- style
		make_style_string({['font-family'] = font, ['style'] = style}),
		
		-- class
		make_attribute_string('class', class),
		
		-- other attributes
		attr
	}
	local attr_string = table.concat(attr_table, ' ')
	
	--[=[
	Make the tagged content.
	]=]
	local content = "<" .. tag .. " " .. attr_string .. ">" .. text
	if not noclose then
		content = content .. "</" .. tag .. ">"
	end
	return content
end

function p.lang(frame)
	local args = getArgs(frame)
	return p._lang(args)
end

return p