Modul:Nifûsa tarîxî/Wîkîdane/ceribandin

--[[
Ji bo {{nifûsa tarîxî/wd}}

To-do:
1. Di çavkaniyê de salan rêz bike.
2. Çima çavkaniyên wekî Popules 2021 xuya nabe? 

--]]

local M = {}
local wikidataIB = require("Modul:WikidataIB")
-- Function to remove HTML tags and unwanted characters from a string
local function cleanString(input)
    return mw.ustring.gsub(input, "<[^>]+>", ""):gsub("[^%p%a%s%d]", "")
end

-- Function to get QID using Modul:WikidataIB
local function getQID()
    return wikidataIB.getQid()
end

-- Function to get references
local function getcavkani(qid)
    return mw.getCurrentFrame():expandTemplate{
        title = "wikidata",
        args = { "qualifier", "references", "preferred-", qid, "P1082", "P585" }
    }
end


local function cleanedcavkani(qid)

	local cavkani = getcavkani(qid)
	
	-- Adjust the pattern to capture the year directly
	local pattern = "%d+%s+([^;]+)%s+(%d+)"
	
	-- Apply the pattern and keep only the captured year
	cavkani = cavkani:gsub(pattern, "%2")
			
	-- Split the cavkani string by space " " character
	local items = {}
	for item in cavkani:gmatch("[^%s]+") do
	    table.insert(items, item)
	end
		
	-- Check each item if it only consists of numbers and ";"
	local cleaned_cavkani = ""
	for i, item in ipairs(items) do
	    if not item:match("^[%d;]+$") then
	        if i == #items then
	            -- Remove the semicolon from the last item
	            item = item:gsub(";", "")
	        end
	        -- If an item does not consist only of numbers and ";", keep it
	        cleaned_cavkani = cleaned_cavkani .. item .. " "
	    end
	end
		-- Trim any trailing spaces
		cavkani = cleaned_cavkani:gsub("%s+$", "")
		cavkani = cavkani:gsub(";", ",")
		-- check if cavkani is empty without dates and comma
		local cavkanitest = cavkani:gsub("%d*,*%s*", "")
		
		-- Check if cavkani is empty
		if cavkanitest == "" then
		    cavkani = mw.getCurrentFrame():expandTemplate{
	        title = "Wîkîdaneyê bibîne",
	        args = { qid = qid, pid = "P1082" }
	    }
		end
			
    return cavkani
end



function M.formatPopulationData(frame)
    local qid = frame.args[1] or frame.args["qid"] or getQID()
    local args = frame:getParent().args
    local align = args["align"] or args["rêz"] or "left"
    local clear = args["clear"] or args["paqijbike"]
    local gelhe = args["gelhe"]
    local title_name
    local popname    
    if gelhe ~= nil then
        popname = "Gelhe"
        title_name = "Gelhe li gorî salan"
    else
        popname = "Nifûs"
        title_name = "Nifûs li gorî salan"        
    end
    if align == "rast" then
        align = "right"
    end

    -- Use Modul:WikidataIB to get QID if not specified
    if not qid then
        return '[[Kategorî:Rûpelên bi Şablon:Nifûsa tarîxî/wd yên vala]]'
    end

    -- Expand Wdib template directly
    local wdibResult = mw.getCurrentFrame():expandTemplate{
        title = "Wdib",
        args = { "P1082", qual = "P585", qid = qid, osd = "no", fwd = "ALL", noicon = "yes" }
    }

    local editAtWikidata = mw.getCurrentFrame():expandTemplate{
        title = "editAtWikidata",
        args = { qid = qid, pid = "P1082" }
    }

    local entries = mw.text.split(wdibResult, ", ")
    local historicalPopulationArgs = {}

    for _, entry in ipairs(entries) do
        local parts = mw.text.split(entry, " ")  -- Split each entry by space
        local date = mw.ustring.gsub(parts[2] or "", "[()]", "")  -- Remove parentheses from the date
        local population = parts[1] or ""
        if date ~= "" and population ~= "" then
            -- Add date and population to historicalPopulationArgs
            table.insert(historicalPopulationArgs, { date = date, population = population })
        end
    end

    -- Sort the date and population pairs based on the date
    table.sort(historicalPopulationArgs, function(a, b) return a.date < b.date end)

    -- Check if there is no data
    if #historicalPopulationArgs == 0 then
        return '[[Kategorî:Rûpelên bi Şablon:Nifûsa tarîxî/wd yên vala]]'
    end
	local cavkani = cleanedcavkani(qid)
    -- Construct Historical Populations template
    local templateArgs = {
        align = align,
        clear = clear,
        pop_name = popname,
        title = title_name,
        source = cavkani .. editAtWikidata
    }

    for _, pair in ipairs(historicalPopulationArgs) do
        table.insert(templateArgs, pair.date)
        table.insert(templateArgs, pair.population)
    end

    -- Expand Historical Populations template
    local historicalPopulationsTemplate = mw.getCurrentFrame():expandTemplate{
        title = "Nifûsa tarîxî",
        args = templateArgs
    }

    return historicalPopulationsTemplate or "Data not found."
end

return M