

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

local prefabs = 
{
    
}

local function onnear(inst)
        inst.AnimState:PlayAnimation("idle")
        inst.Light:Enable(true)
end

local function onfar(inst)
       inst.AnimState:PlayAnimation("idle")     
       inst.Light:Enable(false)
end

local function onhammered(inst, worker)
if inst.components.burnable ~= nil and inst.components.burnable:IsBurning() then
        inst.components.burnable:Extinguish()
    end
	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

        inst.AnimState:PlayAnimation("hit")
        inst.AnimState:PushAnimation("idle", true)
    end
    if inst.components.sleepingbag ~= nil and inst.components.sleepingbag.sleeper ~= nil then
        inst.components.sleepingbag:DoWakeUp()
    end
end

local function onfinished(inst)
	if not inst:HasTag("burnt") then
      --inst.AnimState:PlayAnimation("destroy")
      --inst:ListenForEvent("animover", function(inst, data) inst:Remove() end)
	inst.SoundEmitter:PlaySound("dontstarve/common/tent_dis_pre")
	inst.persists = false              
      --inst:DoTaskInTime(16*FRAMES, function() inst.SoundEmitter:PlaySound                                          ("dontstarve/common/tent_dis_twirl") end)
	end
end

local function onbuilt(inst)
	inst.AnimState:PlayAnimation("place")
	inst.AnimState:PushAnimation("idle", false)
end

local function onignite(inst)
    inst.components.sleepingbag:DoWakeUp()
end
--We don't watch "stop'phase'" because that
--would not work in a clock without 'phase'
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("tent") then
            sleeper.sg.statemem.iswaking = true
        end
        sleeper.sg:GoToState("wakeup")
    end

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

    inst.components.finiteuses:Use()
end

local function onsleeptick(inst, sleeper)
    local isstarving = sleeper.components.beaverness ~= nil and sleeper.components.beaverness:IsStarving()

    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, true)
    end

    if not isstarving and sleeper.components.health ~= nil then
        sleeper.components.health:DoDelta(TUNING.SLEEP_HEALTH_PER_TICK * 2, 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)

    
    inst.AnimState:PlayAnimation("idle", true)
    

    if inst.sleeptask ~= nil then
        inst.sleeptask:Cancel()
    end
    inst.sleeptask = inst:DoPeriodicTask(TUNING.SLEEP_TICK_PERIOD, onsleeptick, nil, sleeper)
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

function fn()
        local inst = CreateEntity()
        inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddSoundEmitter()
    inst.entity:AddMiniMapEntity()
    inst.entity:AddNetwork()
    MakeObstaclePhysics(inst, 2)
        inst:AddTag("structure")	
        inst:AddTag("tent")
		inst:AddTag("nosleepanim")    
		
    
        inst.AnimState:SetBank("wilson_cabin")
        inst.AnimState:SetBuild("wilson_cabin")
        inst.AnimState:PlayAnimation("idle", true)    
        inst.Transform:SetScale(1.10, 1.10, 1.10)

		--inst.MiniMapEntity:SetIcon(icon)
		inst.MiniMapEntity:SetIcon( "wilson_cabin.tex" )
    MakeSnowCoveredPristine(inst)

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end
	inst:AddComponent("inspectable")
        inst:AddComponent("lootdropper")
        inst:AddComponent("workable")
        inst.components.workable:SetWorkAction(ACTIONS.HAMMER)
        inst.components.workable:SetWorkLeft(4)
        inst.components.workable:SetOnFinishCallback(onhammered)
        inst.components.workable:SetOnWorkCallback(onhit)     
    
        inst.entity:AddLight()
        inst.Light:Enable(false)
        inst.Light:SetRadius(6.5)
        inst.Light:SetFalloff(1)
        inst.Light:SetIntensity(.5)
        inst.Light:SetColour(235/255,121/255,12/255)
        inst.Light:EnableClientModulation(true)

        inst:AddComponent("finiteuses")
        inst.components.finiteuses:SetMaxUses(TUNING.FINITEUSES_CABIN)
        inst.components.finiteuses:SetUses(100)
        inst.components.finiteuses:SetOnFinished( onfinished )
	    
        inst:AddComponent("sleepingbag") 
        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:AddComponent( "playerprox" )
        inst.components.playerprox:SetDist(8,9)
        inst.components.playerprox:SetOnPlayerNear(onnear)    
        inst.components.playerprox:SetOnPlayerFar(onfar)
    
	MakeSnowCovered(inst)
    inst:ListenForEvent("onbuilt", onbuilt)

    MakeLargeBurnable(inst, nil, nil, true)
    MakeMediumPropagator(inst)

    inst.OnSave = onsave 
    inst.OnLoad = onload

    MakeHauntableWork(inst)
	inst.sleep_phase = "night"
    inst.sleep_anim = "sleep_loop"
    inst.hunger_tick = TUNING.SLEEP_HUNGER_PER_TICK
    --inst.is_cooling = false
        return inst
end	
return Prefab( "common/objects/wilson_cabin", fn, assets),
		MakePlacer( "common/wilson_cabin_placer", "wilson_cabin", "wilson_cabin", "idle" ) 
