local MOD_NAME = "InstantScan"
local Config = require("config")

local function Log(message)
    if Config.Debug then
        print(string.format("[%s] %s\n", MOD_NAME, message))
    end
end

local function MakeInstant(scanData)
    scanData.ScanDuration = 0.0
    Log("Set ScanDuration to 0.0")
end

Log("Loaded")

local SCAN_CLASS_PATH = "/Script/UWEScanner.UWEScanData"
local SHORT_CLASS_NAME = "UWEScanData"

local registered = false
local _ready = false

local function PatchExisting()
    if Config.Enabled == false then
        return false
    end

    -- local scanDataClass = StaticFindObject(CLASS_PATH)
    -- if not scanDataClass then
    --     return false
    -- end

    -- Patch objects created before our NotifyOnNewObject listener
    local objects = FindAllOf(SHORT_CLASS_NAME)
    if objects then
        for _, scanData in pairs(objects) do
            MakeInstant(scanData)
        end
    end

    return true
end

local function Bootstrap()
    ExecuteInGameThread(function()
        if registered then
            return
        end

        -- local scanDataClass = StaticFindObject(CLASS_PATH)
        -- if not scanDataClass then
        --     Log("UWEScanData not loaded yet")
        --     return
        -- end

        registered = true

        NotifyOnNewObject(SCAN_CLASS_PATH, function(scanData)
            if Config.Enabled == false then
                return
            end

            MakeInstant(scanData)
        end)

        ready = PatchExisting()
    end)
end

-- NOTE: I am still not familiar with events and timing for UE4SS and Subnautica 2.

RegisterLoadMapPostHook(function()
    ExecuteWithDelay(3000, Bootstrap)
end)
