local aliases = {
    width = {'العرض', 'عرض'},
    title = {'عنوان', 'العنوان'},
    shaer = {'الشاعر', 'شاعر'},
    bahar = {'البحر', 'بحر'},
    nass = {1,'النص', 'نص'},
	shaterbyshater = {'شطر شطر'},
	fasil = {'فاصل','separator','fasil'},
	free = {'حر', 'شعر حر'},
}
local string = mw.ustring
local getArgs = require('Module:Arguments with aliases').getArgs

local function validString(s)
	if(type(s) == 'string')	then
		s = mw.text.trim(s) 
		if( s ~= '' ) then return s end
	end
	return nil
end

local function abyat(frame)
	local A = getArgs(frame, {aliases=aliases})
	
	local mashtoor = false
	local header = ''
	local free = A.free and (A.free ~= "0")
	local fasil = A.fasil and string.gsub(A.fasil, '[%%%^%$%(%)%[%]%.%*%+%-%?]', '%%%1') or "\\\\"
	local fasil_s,fasil_e = string.find(mw.text.trim(A.nass),fasil)

	local sdrdiv = '<div class="abyat-sdr">'
	if not fasil_s and not A[2] then
		mashtoor=true
		sdrdiv = '<div>'
	end
	local nass= ""
	local ret = '<div class="abyat-wrapper' .. (mashtoor and ' mashtoor' or '') .. (free and ' free' or '') ..
	(A.shaterbyshater and ' abyat-shaterbyshater' or '') .. 
	'" style="width:' .. (A.width or 'fit-content') .. ';">'
	
    if A.title then
        header = header .. "<center>'''" .. A.title .. "'''</center>"
    end
    if A.shaer then
        header = header .. "<center>" .. A.shaer .. "</center>"
    end
    if A.bahar then
        header = header .. "<center>''[من " .. A.bahar .. "]''</center>"
    end

	-- نمط متوافق مع أساليب القوالب القديمة
	if A[2] then
    	local shater_num =1
    	local aa,bb
    	aa = validString(A[shater_num])
    	bb = validString(A[shater_num+1])
    	while aa  ~= nil or bb ~= nil do
    	    if aa~= nil and bb ~= nil  then
    			ret=ret .. '<div class="abyat-sdr">' ..aa .. "</div>"
    			ret=ret .. '<div class="abyat-ajz">' ..bb .. "</div>\n"
			else
    			ret=ret .. '<div class="abyat-single_bayt">' ..(aa or bb) .. "</div>\n"
			end
    		shater_num=shater_num+2
    		aa = validString(A[shater_num])
    		bb = validString(A[shater_num+1])
		end
	else
	-- نمط أبيات
		nass = mw.text.trim(A.nass)
		if fasil_s == 1 then
	        ret = ret .. '<div class="abyat-single_bayt">'
	        nass = string.sub(nass,fasil_e+1)
	    else
	        ret = ret .. sdrdiv
	    end
	
	    nass=string.gsub(nass,"\n"..fasil,'</div><div class="abyat-single_bayt">')
	    nass=string.gsub(nass,"\n([^|])",'</div>' .. sdrdiv ..'%1')
	    nass=string.gsub(nass, fasil,'</div><div class="abyat-ajz">')
	end
    return header .. ret .. nass .. "</div></div>"
end

return {abyat=abyat}