local assets =
{
	Asset("ANIM", "anim/nightmare_crack_ruins.zip"),
	Asset("ANIM", "anim/nightmare_crack_upper.zip"),
}

local prefabs =
{
	"shadowmaxwell",
    "nightmarefissurefx",
    "upper_nightmarefissurefx"
}

local function turnoff(inst, light)
    if light then
        light:Enable(false)
    end
end

local function fn(Sim)
	local inst = CreateEntity()
	local trans = inst.entity:AddTransform()
	local anim = inst.entity:AddAnimState()
	local sound = inst.entity:AddSoundEmitter()
	local phys = inst.entity:AddPhysics()
	
	anim:SetBuild("nightmare_crack_upper")
    anim:SetBank("nightmare_crack_upper")
    anim:PlayAnimation("idle_closed")
	
	inst:AddComponent("lighttweener")
	
    inst.entity:AddLight()
	inst.components.lighttweener:StartTween(inst.Light, 1, .9, 0.9, {239/255, 194/255, 194/255}, 0, turnoff)
	
	inst:AddTag("shadowfissure")

	inst.fxprefab = "upper_nightmarefissurefx"	
	
	inst:DoTaskInTime(1*FRAMES, function(inst)
		SpawnPrefab("statue_transition").Transform:SetPosition(inst:GetPosition():Get())
		SpawnPrefab("statue_transition_2").Transform:SetPosition(inst:GetPosition():Get())
	end)
	 
	inst:DoTaskInTime(3, function(inst)
		inst.fx = SpawnPrefab(inst.fxprefab)
        local pos = inst:GetPosition()
        inst.fx.Transform:SetPosition(pos.x, -0.1, pos.z)
		inst.Light:Enable(true)
		inst.components.lighttweener:StartTween(nil, 2, nil, nil, nil, 0.5)
        inst.AnimState:PlayAnimation("open_2")
        inst.AnimState:PushAnimation("idle_open")
		inst.fx.AnimState:PlayAnimation("open_1")
		inst.SoundEmitter:PlaySound("dontstarve/cave/nightmare_spawner_open")
	end)
	
	inst:DoTaskInTime(9, function(inst)
		if math.random() > 0.5 and not inst.spawnedmob then
			inst.spawnedmob = true
			SpawnPrefab("statue_transition").Transform:SetPosition(inst:GetPosition():Get())
			SpawnPrefab("statue_transition_2").Transform:SetPosition(inst:GetPosition():Get())
			SpawnPrefab("shadowmaxwell").Transform:SetPosition(inst:GetPosition():Get())
		end
	end)
	
	inst:DoTaskInTime(18, function(inst)
		inst.Light:Enable(false)
		inst.AnimState:PushAnimation("close_2") 
		inst.AnimState:PushAnimation("idle_closed")
		inst.fx.AnimState:PushAnimation("close_2") 
		inst.fx.AnimState:PushAnimation("idle_closed")
		inst.SoundEmitter:PlaySound("dontstarve/cave/nightmare_spawner_close")
	end)
	
	inst:DoTaskInTime(24, function(inst)
		SpawnPrefab("statue_transition").Transform:SetPosition(inst:GetPosition():Get())
		SpawnPrefab("statue_transition_2").Transform:SetPosition(inst:GetPosition():Get())
		inst.fx:Remove()
		inst:Remove()
	end)
	
	inst.OnSave = function(inst, data)
		if inst.spawnedmob then 
			data.spawnedmob = inst.spawnedmob
		end
    end     
    
    inst.OnLoad = function(inst, data) 
		if data and data.spawnedmob then
			inst.spawnedmob = data.spawnedmob
		end
    end
    return inst
end

return Prefab("common/shadowfissure", fn, assets, prefabs)