-- Lampovo Project ^ω^ Average Enjoyer

filenameRewritePatch = {}

g_xmlManager:addCreateSchemaFunction(function ()
    filenameRewritePatch.xmlSchema = XMLSchema.new("overridePaths")
end)

local filenameRewriteHandlers = filenameRewriteHandlers or {}
local modDir = g_currentModDirectory

local overridePaths = {}
local xmlFile = XMLFile.load("overridePathsXml", modDir .. "xml/overridePaths.xml")

if xmlFile ~= nil then
    for _, key in xmlFile:iterator("overridePaths.overridePath") do
        local original = xmlFile:getString(key .. "#original")
        local newPath = xmlFile:getString(key .. "#new")
        if original and newPath then
            overridePaths[original] = newPath
        end
    end

    xmlFile:delete()
end

table.insert(filenameRewriteHandlers, function(filename, baseDir)
    filename = overridePaths[filename] or filename

    return filename, baseDir
end)

local function inj_utils_getFilename(filename, superFunc, baseDir)
    if filename == nil then
        return nil
    end

    for _, handler in ipairs(filenameRewriteHandlers) do
        filename, baseDir = handler(filename, baseDir)
    end

    if type(filename) == "string" then
        local modPrefix = "$moddir$"

        if filename:lower():sub(1, #modPrefix) == modPrefix then
            local startIndex = #modPrefix + 1
            local slashStart, slashEnd = filename:find("/", startIndex)
            local modName = filename:sub(startIndex, slashStart - 1)
            baseDir = g_modNameToDirectory and g_modNameToDirectory[modName]
            filename = filename:sub(slashEnd + 1)
        end
    end

    return superFunc(filename, baseDir)
end

Utils.getFilename = Utils.overwrittenFunction(Utils.getFilename, inj_utils_getFilename)