local assets =
{
    Asset("ANIM", "anim/cave_entrance.zip"),
    Asset("ANIM", "anim/ruins_entrance.zip"),
	Asset("MINIMAP_IMAGE", "cave_closed"),
	Asset("MINIMAP_IMAGE", "cave_open"),
	Asset("MINIMAP_IMAGE", "cave_no_access"),
	Asset("MINIMAP_IMAGE", "cave_overcapacity"),
	Asset("MINIMAP_IMAGE", "ruins_closed"),
}

local prefabs =
{
    "bat",
    "rock_break_fx",
}



--local function activate(inst)
    -- nothing
--end

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 OnIsDay(inst, isday)
    if isday then
	
	          inst.components.childspawner:StopRegen()
        inst.components.childspawner:StopSpawning()
       ReturnChildren(inst)
    else

        inst.components.childspawner:StartSpawning()
    end
end

local function OnIsNewMoon(inst)

if TheWorld.state.moonphase == "new" then
       inst.components.childspawner:StartRegen()
	   else
	          inst.components.childspawner:StopRegen()

end
end


local function canspawn(inst)

  local days_survived = TheWorld.state.cycles
    return days_survived >= 20
end


local function fn(isbackground)
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddSoundEmitter()
    inst.entity:AddMiniMapEntity()
    inst.entity:AddNetwork()

    MakeObstaclePhysics(inst, 0.5)



    inst.AnimState:SetBank("cave_entrance")
    inst.AnimState:SetBuild("cave_entrance")
    inst.AnimState:PlayAnimation("open")
    if isbackground then
        inst.AnimState:SetLayer(LAYER_BACKGROUND)
        inst.AnimState:SetSortOrder(3)
    end
     inst.AnimState:SetMultColour(0.2, 0.1, 0.1, 1)
		inst.Transform:SetScale(0.5, 0.5, 0.5)
	
    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end


	    inst:AddComponent("childspawner")
    inst.components.childspawner:SetRegenPeriod(1)
    inst.components.childspawner:SetSpawnPeriod(.1)
    inst.components.childspawner:SetMaxChildren(1)
    inst.components.childspawner.childname = "shadowbatenemy"
    inst.components.childspawner.canspawnfn = canspawn
	
	OnIsDay(inst, TheWorld.state.isday)
    inst:WatchWorldState("isday", OnIsDay)
	
	OnIsNewMoon(inst, TheWorld.state.moonphase == "new")	
	inst:WatchWorldState("isnewmoon", OnIsNewMoon)

    inst:AddComponent("inspectable")


    return inst
end


return Prefab("shadowbatcave", fn, assets, prefabs)

