local p = {}
local wd2 = require('Module:wikidata2')
local Frame;
local Category = {}
Category["remove"] = " [[تصنيف:صفحات بها وصلات للإزالة]]"
Category["review"] = " [[تصنيف:وصلات إنترويكي بحاجة لمراجعة|%s]]"
Category["nositelinks"] = " [[تصنيف:صفحات بها قالب:Ill-WD2 دون وصلات لغات|%s]]"
Category["add"] = "[[تصنيف:صفحات بها وصلات إنترويكي|%s]]"

function makeCategory(key,args)
	line = Category[key]
	if key ~= 'add' and Frame.args["nocat"] and Frame.args["nocat"] ~= '' then
		return ''
	end
	return line
end
	
function labelIn(langcode,id)
	local label, lange = mw.wikibase.getLabelWithLang( id )
	if lange == langcode
	then
		return label
	else
		--mw.log("Module:Ill-WD2: label = " ..label .. "lange = " ..lange .. "langcode = " .. langcode)
		return ""
	end
end
function maketext(String)
	local y = Frame.args["y"]
	local text = Frame.args["text"] or Frame.args["نص"]
	if text and text ~= ""  then
			return text 
	elseif y and y ~= ""  then
		String2 = mw.ustring.gsub( String , '–', '-' )
		ca = mw.ustring.match( String2 , "%d%d%d%d%-%d%d%d%d", 1 ) or mw.ustring.match( String2 , "%d%d%-%d%d%d%d", 1 ) or mw.ustring.match( String2 , "%d%d%d%d%-%d%d", 1 )
		ca = ca or mw.ustring.match( String2 , "%d%d%d%d", 1 ) or  String
		return ca
	end	
	return String
end

function make_suffix(id , target_Site , target_Link , sitelinks_count, fromlua) 
	if sitelinks_count == 0 then
		if fromlua == "" then 
			return string.format(makeCategory("nositelinks") , ( id or "1" ) )
		end
	end
	local other_lang = '"'.. id ..'" في لغات أخرى'
	--local other_lang = '<span title="'.. other_lang ..'">لغات أخرى</span>'
	--local other_lang =  mw.text.tag('span', {title= other_lang }, "لغات أخرى")
	local other_lang =  '<sup class=reference title="'.. other_lang..'">[لغات أخرى]</sup>'

	local other_lang_text = '&nbsp;[[d:'.. id ..'#sitelinks-wikipedia|' ..other_lang..']]'
	--local suff = '<span class="noprint" style="font-size: smaller; font-style: normal; font-weight: normal;">' .. other_lang_text.. '</span>'
	local suff = '' .. mw.text.tag('span'
		, {class= "noprint"
		, style="font-size: smaller; font-style: normal; font-weight: normal;"}
		, other_lang_text)
	
	if (target_Link and target_Link ~= "") and (target_Site and target_Site ~= "") then
		--language = '{{#language:'.. target_Site ..'|ar}}'
		language = Frame:callParserFunction('#language', target_Site , "ar")
		suff = '[[:'.. target_Site ..':'.. target_Link ..'|<sup class=reference title="'.. target_Link ..'">['.. language ..']</sup>]]'
	end
	--suffe = Frame:preprocess("&nbsp;" .. suff) --suff
	suffe = "&nbsp;" .. suff
	tt =  string.format (makeCategory("add") , ( id or "1" ) )
	--if fromlua == "" then tt = "" end
	return suffe .. tt
end

function make_ar_link(title, suffix,id, sitelinks_count)
	local text = maketext(title)
	local link;
	local tit = mw.title.new(title)
    local cate = string.format (makeCategory("review") , ( id or "1" ) )
    local nositelinks = string.format(makeCategory("nositelinks") , ( id or "1" ) )
	if tit and tit.exists then
		link = text .. suffix .. cate
        mw.log( 'Module:Ill-WD2: review "' .. title .. '", id: ' .. id)
        --mw.log(cate)
	else
		title = mw.ustring.gsub(title , "^تصنيف:", "")
		text = mw.ustring.gsub(text , "^تصنيف:", "")
		link = '[[' .. title .. "|" .. text .. "]]" .. suffix
	end
	if sitelinks_count == 0 then link = text .. suffix end
	return link
end

function sitelink( id , site )
	local site = site or 'arwiki'
	local link = mw.wikibase.sitelink( id , site ) or ""
	--mw.log("Module:Ill-WD2: mw.wikibase.sitelink : " .. link)
	return link
end

function p.link(frame)
	Frame = frame;
	local target_label;
	local ar_link;
	local en_label = ""
	local pframe = frame:getParent()
    Frame = pframe
	local fromlua = pframe.args["fromlua"] or ""
	local id = pframe.args["id"] or pframe.args[2]
	if not id or id == "" then return "No ID" end
	local lab_1 = pframe.args[1] or pframe.args["label"]
	local target_SiteLink = ""
	local target = pframe.args["target"] or pframe.args["لغ"] or ""
	if pframe.args["en"] and pframe.args["en"] ~= "" then
		 target = "en" 
		 --mw.log("Module:Ill-WD2: target = en" )
	elseif target == "en" then
		 en_label = labelIn("en",id)
		end
	if target ~= "" then target_SiteLink = sitelink( id , target .. "wiki" ) end
	local SiteLink =  mw.wikibase.sitelink( id )
	local sitelinks_count =  wd2.countSiteLinks( id )
	if SiteLink 
		then 
			Link = '[[' .. SiteLink .. "|" .. maketext(SiteLink) .. "]]"
			--mw.log("Module:Ill-WD2: replace: " .. id .. " by: " .. Link)
			return Link .. makeCategory("remove")
	end
	local ar_label = labelIn("ar",id)
	local suffix = make_suffix(id , target , target_SiteLink , sitelinks_count, fromlua )
	if lab_1 and lab_1 ~= "" 
		then ar_link = lab_1 
	elseif ar_label ~= ""
		then ar_link = ar_label
	end
	if ar_link and ar_link ~= "" then
		--mw.log("Module:Ill-WD2: ar_link : " .. ar_link)
		return make_ar_link(ar_link , suffix , id , sitelinks_count )
	end
	if en_label ~= ""  then
		--mw.log("Module:Ill-WD2: en_label " .. en_label)
		return maketext(en_label) ..  make_suffix(id , "" , "" , sitelinks_count , fromlua )
	end
	if target ~= "" and target_SiteLink ~= "" then
		--mw.log("Module:Ill-WD2: target " .. target .. ": " .. target_SiteLink)
		return maketext(target_SiteLink) .. suffix
	end
	--mw.log("Module:Ill-WD2: nothing en_label: " .. en_label  )
	return ""
end

return p