require "prefabutil"

local assets =
{
    Asset("ANIM", "anim/spider_cocoon.zip"),
    Asset("SOUND", "sound/spider.fsb"),
	Asset("MINIMAP_IMAGE", "spiderden"), --shared with spiderden2 and 3
}

local prefabs =
{
    --"merm",
    "collapse_big",

    --loot:
    --"logs",
    --"rocks",
    --"fish",
}

SetSharedLootTable('catcoonden_p',
{
    {'logs', 1.00},
    {'logs', 1.00},
	{'logs', 1.00},
})

local loot =
{
	"charcoal",
	"charcoal",
	"rocks",
	"rocks",
	"rocks",

}



local function PlayLegBurstSound(inst)
    inst.SoundEmitter:PlaySound("dontstarve/creatures/spiderqueen/legburst")
end


local function onhammered(inst, worker)
	inst.components.sleepingbag:DoWakeUp()
    if inst.components.burnable ~= nil and inst.components.burnable:IsBurning() then
        inst.components.burnable:Extinguish()
    end
    inst:RemoveComponent("childspawner")
    inst.components.lootdropper:DropLoot()
    local fx = SpawnPrefab("collapse_big")
    fx.Transform:SetPosition(inst.Transform:GetWorldPosition())
    fx:SetMaterial("wood")
    inst:Remove()
end

local function onhit(inst, worker)
    if not inst:HasTag("burnt") then
        if inst.components.childspawner ~= nil then
            inst.components.childspawner:ReleaseAllChildren(worker)
        end
        inst.AnimState:PlayAnimation("bubble_lava")
    end
end

local function onbuilt(inst)
    --inst.AnimState:PlayAnimation("place")
    inst.AnimState:PushAnimation("bubble_lava", true)
end

local function OnCollide(inst, other)
    if other ~= nil and not other:HasTag("lavae") and
        other:IsValid() and
        inst:IsValid() and
        other.components.burnable ~= nil and
        other.components.fueled == nil then
        other.components.burnable:Ignite(true, inst)
    end
end

local function OnEntityWake(inst)
    --inst.SoundEmitter:PlaySound("dontstarve/creatures/hound/mound_LP", "loop")
end

local function OnEntitySleep(inst)
    --inst.SoundEmitter:KillSound("loop")
end

local function onsave(inst, data)
    if inst:HasTag("burnt") or (inst.components.burnable ~= nil and inst.components.burnable:IsBurning()) then
        data.burnt = true
    end
end

local function onload(inst, data)
    if data ~= nil and data.burnt then
        inst.components.burnable.onburnt(inst)
    end
end

local function onignite(inst)
    inst.components.sleepingbag:DoWakeUp()
end

local function onburntup(inst)
    --inst.AnimState:PlayAnimation("burnt_rundown")
end

local function wakeuptest(inst, phase)
    --if phase ~= inst.sleep_phase then
        --inst.components.sleepingbag:DoWakeUp()
    --end
end

local function onwake(inst, sleeper, nostatechange)
    if inst.sleeptask ~= nil then
        inst.sleeptask:Cancel()
        inst.sleeptask = nil
    end
	
    inst:StopWatchingWorldState("phase", wakeuptest)
    sleeper:RemoveEventCallback("onignite", onignite, inst)

    if not nostatechange then
        if sleeper.sg:HasStateTag("house_sleep") then
            sleeper.sg.statemem.iswaking = true
        end
		--inst.SoundEmitter:PlaySound("dontstarve/common/pighouse_door")
        sleeper.sg:GoToState("taunt")
    end

    if inst.sleep_anim ~= nil then
        inst.AnimState:PushAnimation("bubble_lava", true)
    end

    --inst.components.finiteuses:Use()
end

local function OnKilled(inst)
    inst.AnimState:PlayAnimation("death", false)
    --inst.SoundEmitter:KillSound("loop")
    inst.components.lootdropper:DropLoot(inst:GetPosition())
end

local function onsleeptick(inst, sleeper)
    local isstarving = sleeper.components.beaverness ~= nil and sleeper.components.beaverness:IsStarving()
	
	if not sleeper:HasTag("lavae") then
		--print ("Too bad he isn't a spider!")
		 inst.components.sleepingbag:DoWakeUp()
	end
	
    if sleeper.components.hunger ~= nil then
        sleeper.components.hunger:DoDelta(inst.hunger_tick, true, true)
        isstarving = sleeper.components.hunger:IsStarving()
    end

    if sleeper.components.sanity ~= nil and sleeper.components.sanity:GetPercentWithPenalty() < 1 then
        sleeper.components.sanity:DoDelta(TUNING.SLEEP_SANITY_PER_TICK * 2, true)
    end

    if not isstarving and sleeper.components.health ~= nil then
        sleeper.components.health:DoDelta(TUNING.SLEEP_HEALTH_PER_TICK, true, inst.prefab, true)
    end

    if sleeper.components.temperature ~= nil then
        if inst.is_cooling then
            if sleeper.components.temperature:GetCurrent() > TUNING.SLEEP_TARGET_TEMP_TENT then
                sleeper.components.temperature:SetTemperature(sleeper.components.temperature:GetCurrent() - TUNING.SLEEP_TEMP_PER_TICK)
            end
        elseif sleeper.components.temperature:GetCurrent() < TUNING.SLEEP_TARGET_TEMP_TENT then
            sleeper.components.temperature:SetTemperature(sleeper.components.temperature:GetCurrent() + TUNING.SLEEP_TEMP_PER_TICK)
        end
    end

    if isstarving then
        inst.components.sleepingbag:DoWakeUp()
    end
end

local function onsleep(inst, sleeper)
    --inst:WatchWorldState("phase", wakeuptest)
    sleeper:ListenForEvent("onignite", onignite, inst)
	--print ("someone wants to sleep in the den!")
	
	
    --if inst.sleep_anim ~= nil then
        --inst.AnimState:PlayAnimation(inst.sleep_anim, true)
    --end

    if inst.sleeptask ~= nil then
        inst.sleeptask:Cancel()
    end
	
	--if sleeper:HasTag("spider") then
	--inst.SoundEmitter:PlaySound("dontstarve/common/pighouse_door")
    inst.sleeptask = inst:DoPeriodicTask(TUNING.SLEEP_TICK_PERIOD, onsleeptick, nil, sleeper)
	
	--end
end

--local function OnIsDay(inst, isday)
    --if isday then
        --StopSpawning(inst)
    --elseif not inst:HasTag("burnt") then
        --if not TheWorld.state.iswinter then
            --inst.components.childspawner:ReleaseAllChildren()
        --end
        --StartSpawning(inst)
    --end
--end

--local function OnHaunt(inst)
    --if inst.components.childspawner == nil or
       --- not inst.components.childspawner:CanSpawn() or
        --math.random() > TUNING.HAUNT_CHANCE_HALF then
        --return false
    --end

    --local target = FindEntity(inst, 25, nil, { "character" }, { "merm", "playerghost", "INLIMBO" })
    --if target == nil then
        --return false
    --end

    --onhit(inst, target)
    --return true
--end

local function MakeDenFn()
	return function()
    local inst = CreateEntity()

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

    --MakeObstaclePhysics(inst, 0.5)

	
	inst.hunger_tick = 0
	
	--MakeSnowCoveredPristine(inst)
	
	 MakeSmallObstaclePhysics(inst, 1.95)

    inst.MiniMapEntity:SetIcon("pond_lava.png")

    inst.AnimState:SetBuild("lava_tile")
    inst.AnimState:SetBank("lava_tile")
    inst.AnimState:PlayAnimation("bubble_lava", true)
    inst.AnimState:SetOrientation(ANIM_ORIENTATION.OnGround)
    inst.AnimState:SetLayer(LAYER_BACKGROUND)
    inst.AnimState:SetSortOrder(3)

    inst:AddTag("structure")
    inst:AddTag("lava")
	inst:AddTag("maggothouse")
	inst:AddTag("cooker")

	inst:AddComponent("cooker")
	
	inst.mobhouse = true
	
	inst.no_wet_prefix = true
	
	inst:AddComponent("heater") 
	inst.components.heater.heat = 500
	
	inst.Physics:SetCollisionCallback(OnCollide)
	
	inst.Light:Enable(true)
    inst.Light:SetRadius(1.5)
    inst.Light:SetFalloff(0.66)
    inst.Light:SetIntensity(0.66)
    inst.Light:SetColour(235 / 255, 121 / 255, 12 / 255)
		
    --MakeSnowCoveredPristine(inst)

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end
	
	-------------------
    --inst:AddComponent("health")
    --inst.components.health:SetMaxHealth(300)
    --inst:ListenForEvent("death", OnKilled)

    -------------------
	
	inst:AddComponent("workable")
	inst:AddComponent("sleepingbag")
	--MakeHauntableWork(inst)
    inst.components.sleepingbag.onsleep = onsleep
    inst.components.sleepingbag.onwake = onwake
    --convert wetness delta to drying rate
    inst.components.sleepingbag.dryingrate = math.max(0, -TUNING.SLEEP_WETNESS_PER_TICK / TUNING.SLEEP_TICK_PERIOD)

	
	inst.components.workable:SetWorkAction(ACTIONS.DIG)
    inst.components.workable:SetWorkLeft(1)
    inst.components.workable:SetOnFinishCallback(onhammered)
    inst.components.workable:SetOnWorkCallback(onhit)
	
    inst:AddComponent("lootdropper")
    --inst.components.lootdropper:SetChanceLootTable('catcoonden_p')
	inst.components.lootdropper:SetLoot(loot)

    inst:AddComponent("hauntable")
    inst.components.hauntable:SetHauntValue(TUNING.HAUNT_SMALL)
    --inst.components.hauntable:SetOnHauntFn(OnHaunt)
	
	inst.data = {}
	
    --inst:WatchWorldState("isday", OnIsDay)

    --StartSpawning(inst)


        ---------------------
       -- MakeMediumPropagator(inst)


    inst:AddComponent("inspectable")

    MakeSnowCovered(inst)
	
	inst.OnEntitySleep = OnEntitySleep
        inst.OnEntityWake = OnEntityWake

    return inst
	end
end

return Prefab("lavapond_p", MakeDenFn(), assets, prefabs),
	--Prefab("spidernest2_p", fn(2), assets, prefabs),
	--Prefab("spidernest3_p", fn(3), assets, prefabs),
	MakePlacer("lavapond_p_placer", "lava_tile", "lava_tile", "bubble_lava")
