--==[ ЗАЩИТА И ЗАКРЫТИЕ ВХОДА В ПЕЩЕРУ ]==--

local SpawnPrefab = GLOBAL.SpawnPrefab

if not GLOBAL.TheNet:GetIsServer() then return end

AddPrefabPostInit("cave_entrance_open", function(inst)
    local function ToggleChildren(butterfly)
		inst:StopAllWatchingWorldStates()
		
		local function ReturnChildren(inst)
    		for k, child in pairs(inst.components.childspawner.childrenoutside) do
        		if child.components.homeseeker ~= nil then
            		child.components.homeseeker:GoHome()
        		end
        		child:PushEvent("gohome")
    		end
		end
		
		local function ToggleSpawn(inst, allowed)
    		if allowed then
				inst.components.childspawner:StopRegen()
        		inst.components.childspawner:StartSpawning()
			else
				inst.components.childspawner:StartRegen()
        		inst.components.childspawner:StopSpawning()
				ReturnChildren(inst)
			end
		end
		
		local function ToggleUpdate(inst)
    		local state = GLOBAL.TheWorld.state
			if butterfly then
				ToggleSpawn(inst, state.isday and not state.iswinter)
			else
				ToggleSpawn(inst, not state.isday)
			end
		end
		
		ToggleUpdate(inst)
		if butterfly then
			inst.components.childspawner.childname = "butterfly"
			
			inst:AddTag("guarded")
			inst:WatchWorldState("isday", ToggleUpdate)
			inst:WatchWorldState("iswinter", ToggleUpdate)
		else		
			inst.components.childspawner.childname = "bat"
			
			inst:RemoveTag("guarded")
			inst:WatchWorldState("isday", ToggleUpdate)
		end
	end
	
	inst:DoPeriodicTask(5, function()
		local x, y, z = inst.Transform:GetWorldPosition()
		local ents = TheSim:FindEntities(x, y, z, 2, { "molebait", "cattoy" }, { "FX", "NOCLICK", "DECOR" })

        local is_guardian_here, recently_guarded = false, inst:HasTag("guarded")
		for k, v in ipairs(ents) do
			if v.prefab == "trinket_4" or v.prefab == "trinket_13" then
				if v.components.hauntable and math.random() < 0.5 then
					v.components.hauntable:DoHaunt()
				end
				is_guardian_here = true
			end
		end

		if (is_guardian_here and not recently_guarded)
		or (not is_guardian_here and recently_guarded) then
			ToggleChildren(is_guardian_here)
		end
	end)
end)

AddPrefabPostInit("gunpowder", function(inst)
    local OldOnExplodeFn = inst.components.explosive.onexplodefn
	local function OnExplodeFn(inst)
		OldOnExplodeFn(inst)
		
		local x, y, z = inst.Transform:GetWorldPosition()
		local range = inst.components.explosive.explosiverange
		
		for _,v in pairs(TheSim:FindEntities(x, y, z, range, { "migrator", "blocker" }, { "CLASSIFIED" })) do
			if v.prefab == "cave_entrance_open" then
				local compound_walls = #TheSim:FindEntities(x, y, z, range, { "wall", "stone" })
				local compound_boulders = #TheSim:FindEntities(x, y, z, range, { "heavy", "boulder", "caveindebris" })
				local mass = compound_walls + compound_boulders * 2
				
				if mass >= 3 then
					v:DoTaskInTime(0.15, function() --black screen frame
						local pt = v:GetPosition()
        				SpawnPrefab("cavein_dust_low").Transform:SetPosition(pt.x, pt.y + 0.1, pt.z)
					
						local closeinst = SpawnPrefab("cave_entrance")
        				closeinst.Transform:SetPosition(pt:Get())
        				closeinst.components.worldmigrator.id = v.components.worldmigrator.id
        				closeinst.components.worldmigrator.linkedWorld = v.components.worldmigrator.linkedWorld
        				closeinst.components.worldmigrator.receivedPortal = v.components.worldmigrator.receivedPortal
					
        				v:Remove()
					end)
				end
			end
        end
	end
	
	inst.components.explosive:SetOnExplodeFn(OnExplodeFn)
end)