local sdk = sdk
local require = require
local string = string
local imgui = imgui
local tostring = tostring

local Core = require("_CatLib")

local mod = Core.NewMod("Auto Fix Camps")

if mod.Config.SystemLog == nil then
    mod.Config.SystemLog = true
end


mod.HookFunc("app.cGUIMapController", "requestOpen(app.GUIMapDef.MapViewMode, app.GUIMapDef.MapOpenType, app.FieldDef.STAGE)",
function (args)
    local tents = Core.FindComponents("app.Gm100_000")

    local msg = ""

    Core.ForEach(tents, function (tent, i)
        local camp = tent._OwnerGimmick

        -- idk why but sometimes tent is broken but camp is not
        -- in this case if i try to repair it and quick travel, game crashed, can't reproduce
        if tent._IsBroken and (camp._IsBrokenTent or camp._IsRepopWait) then
            camp:repairTent()
            if mod.Config.SystemLog then
                Core.SendMessage("Camp %d fixed", i)
            end
        else
            if mod.Config.Debug then
                Core.SendMessage("Camp %d: %s %s %s", i, tostring(tent._IsBroken), tostring(camp._IsBrokenTent), tostring(camp._IsRepopWait))
            end
        end
    end)

end, function (retval)
    return retval
end)


mod.Menu(function ()
	local configChanged = false
    local changed = false

    changed, mod.Config.SystemLog = imgui.checkbox("Display System Notification", mod.Config.SystemLog)
    configChanged = configChanged or changed

    return configChanged
end)
