require('strict')
local p = {}
local data = mw.loadData('Module:BattleHonour/data')
local getArgs = require('Module:Arguments').getArgs

function p.BattleHonourTable(frame)
     -- Convert key-value pairs into a list of {code, data[code]} pairs
     local pairsList = {}
     for code, values in pairs(data) do
         table.insert(pairsList, {code, values})
     end
 
     -- Sort the list based on the "Description" field of each pair
     table.sort(pairsList, function(a, b)
         return a[2].Name < b[2].Name
     end)
 
     -- Generate wiki table code for the sorted list
     local tableCode = "{| class=\"wikitable sortable\"\n"
     tableCode = tableCode .. "|-\n"
     tableCode = tableCode .. "! Code !! Name !! Image !! Description\n"
 
     for i, pair in ipairs(pairsList) do
         local code, values = pair[1], pair[2]
         local name = values.Name or ""
         local image = values.Image or ""
         local description = values.Description or ""
         local pagelink = values.Link or ""

         tableCode = tableCode .. "|-\n"
         tableCode = tableCode .. "|" .. code .. "\n"
         tableCode = tableCode .. "|" .. name .. "\n"
         tableCode = tableCode .. "|[[File:" .. image .. "|x12px|link=" .. pagelink .."]]\n"
         tableCode = tableCode .. "|" .. description .. "\n"
     end
 
     tableCode = tableCode .. "|}"
     return tableCode
	
end

function p.GetBattleHonour(BHCode, imgsize)
	
	local output = ''
	if not data[BHCode] then
		output = "Unknown: <b>" .. BHCode .. "</b>"
		output = output .. "<p> Please see the [[Template:BattleHonour]] for help</p>".. "\n|-\n"
	else
		if string.len(data[BHCode].Link) < 1 then
			output =  "[[File:" ..  data[BHCode].Image .. "|border|" .. imgsize .. "|"  .. data[BHCode].Name .."]]" .. "\n|-\n"
		else
			output = output .. "[[File:" ..  data[BHCode].Image .. "|border|" .. imgsize .. "|link=" .. data[BHCode].Link .. "|" .. data[BHCode].Name .."]]" .. "\n|-\n"
		end
	end
	return output
end

local function makeRow(battleHonours, country, imgsize)
    local row = {style = "text-align:center;"}
    for i, bh in ipairs(battleHonours) do
        if bh ~= "" then
			-- local rowoutput= "[[File:" .. data[bh].Image .. "|border|x20px|link=" .. data[bh].Link .. "|" ..data[bh].Name .. "]]\n|-\n"
			local rowoutput = p.GetBattleHonour(bh, imgsize)
			table.insert(row,string.format('|style="text-align: center"| %s',rowoutput) )
        end
    end
    return table.concat(row, "\n")
end

function p.BHTable(frame)
    local templateArgs = getArgs(frame)
    local classes = {"wikitable"}
    if templateArgs.float then
        table.insert(classes, templateArgs.float)
    end
    local caption = templateArgs.caption or "Battle Honours"
    local title = templateArgs.Title or "Awarded"
    local country = templateArgs.country or "ZAR"
	local imgsize = templateArgs.size or "x20px"
    local battleHonours = {}
    for i = 1, 40 do -- 40 is the max number of params that will be examined. 
        local bh = templateArgs[i] or ""
        if bh ~= "" then
            table.insert(battleHonours, bh)
        end
    end
    if templateArgs.list then
        battleHonours = mw.text.split(templateArgs.list, "%s*,%s*")
    end
    if templateArgs.unlinked then
        return table.concat(battleHonours, ", ")
    end
    local rows = {}
    table.insert(rows, string.format("|+ %s \n", caption))
    table.insert(rows, string.format("|-\n!style=\"width:20%%; background:lightgrey; text-align:center;\"|%s\n|-", title))
    table.insert(rows, makeRow(battleHonours, country, imgsize))
    local outputTable = string.format('{| class="%s" style="margin:0.5em auto; font-size:95%%; border-bottom:5px solid %s; border-top:5px solid %s; width:50%%;"\n%s\n|}', table.concat(classes, " "), templateArgs.borderColor or "#CF9C65", templateArgs.borderColor or "#CF9C65", table.concat(rows, "\n"))

	return outputTable
end

return p
-- Initial Code by John Dovey (13 April 2023) [[User:BoonDock]]