require "prefabutil"
require "recipes"

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

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

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

local loot =
{
    "boards",
    "rocks",
    
}

local function onhammered(inst, worker)
    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("hit_rundown")
        inst.AnimState:PushAnimation("rundown")
    end
end

--local function StartSpawning(inst)
    --if not inst:HasTag("burnt") and
       -- not TheWorld.state.iswinter and
        --inst.components.childspawner ~= nil then
        --inst.components.childspawner:StartSpawning()
    --end
--end

--local function StopSpawning(inst)
    --if not inst:HasTag("burnt") and inst.components.childspawner ~= nil then
        --inst.components.childspawner:StopSpawning()
    --end
--end

--local function OnSpawned(inst, child)
    --if not inst:HasTag("burnt") then
        --inst.SoundEmitter:PlaySound("dontstarve/common/pighouse_door")
        --if TheWorld.state.isday and
           -- inst.components.childspawner ~= nil and
           -- inst.components.childspawner:CountChildrenOutside() >= 1 and
            --child.components.combat.target == nil then
            --StopSpawning(inst)
        --end
    --end
--end

--local function OnGoHome(inst, child)
    --if not inst:HasTag("burnt") then
        --inst.SoundEmitter:PlaySound("dontstarve/common/pighouse_door")
        --if inst.components.childspawner ~= nil and
            --inst.components.childspawner:CountChildrenOutside() < 1 then
            --StartSpawning(inst)
        --end
    --end
--end

local function onbuilt(inst)
    inst.AnimState:PlayAnimation("place")
    inst.AnimState:PushAnimation("rundown")
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("tent") then
            sleeper.sg.statemem.iswaking = true
        end
		inst.SoundEmitter:PlaySound("dontstarve/common/pighouse_door")
        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)
	

    --if inst.sleep_anim ~= nil then
        --inst.AnimState:PlayAnimation(inst.sleep_anim, true)
    --end

    if inst.sleeptask ~= nil then
        inst.sleeptask:Cancel()
    end
	
	
	inst.SoundEmitter:PlaySound("dontstarve/common/pighouse_door")
    inst.sleeptask = inst:DoPeriodicTask(TUNING.SLEEP_TICK_PERIOD, onsleeptick, nil, sleeper)
	
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 fn()
    local inst = CreateEntity()

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

    MakeObstaclePhysics(inst, 1)

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

    inst.AnimState:SetBank("pig_house")
    inst.AnimState:SetBuild("pig_house")
    inst.AnimState:PlayAnimation("rundown")
	
	inst.hunger_tick = TUNING.SLEEP_HUNGER_PER_TICK
	
	inst:AddTag("tent")
    inst:AddTag("structure")

    MakeSnowCoveredPristine(inst)

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end
	
	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: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:ListenForEvent("onbuilt", onbuilt)
	
	
    inst:AddComponent("lootdropper")
    inst.components.lootdropper:SetLoot(loot)
    inst:AddComponent("workable")
    inst.components.workable:SetWorkAction(ACTIONS.HAMMER)
    inst.components.workable:SetWorkLeft(2)
    inst.components.workable:SetOnFinishCallback(onhammered)
    inst.components.workable:SetOnWorkCallback(onhit)

    --inst:AddComponent("childspawner")
    --inst.components.childspawner.childname = "merm"
    --inst.components.childspawner:SetSpawnedFn(OnSpawned)
    --inst.components.childspawner:SetGoHomeFn(OnGoHome)
    --inst.components.childspawner:SetRegenPeriod(TUNING.TOTAL_DAY_TIME * 4)
    --inst.components.childspawner:SetSpawnPeriod(10)
    --inst.components.childspawner:SetMaxChildren(TUNING.MERMHOUSE_MERMS)

    --inst.components.childspawner.emergencychildname = "merm"
    --inst.components.childspawner:SetEmergencyRadius(TUNING.MERMHOUSE_EMERGENCY_RADIUS)
    --inst.components.childspawner:SetMaxEmergencyChildren(TUNING.MERMHOUSE_EMERGENCY_MERMS)

    inst:AddComponent("hauntable")
    inst.components.hauntable:SetHauntValue(TUNING.HAUNT_SMALL)
    --inst.components.hauntable:SetOnHauntFn(OnHaunt)

    --inst:WatchWorldState("isday", OnIsDay)

    --StartSpawning(inst)

    MakeMediumBurnable(inst, nil, nil, true)
    MakeLargePropagator(inst)
    inst:ListenForEvent("onignite", onignite)
    inst:ListenForEvent("burntup", onburntup)

    inst:AddComponent("inspectable")

    MakeSnowCovered(inst)

    return inst
end

local function mermhouseplayer()
    local inst = common_fn("mermhouse_player", "mermhouse_player", "mermhouse.png")

    if not TheWorld.ismastersim then
        return inst
    end

    inst.sleep_phase = "night"
    --inst.sleep_anim = "sleep_loop"
    inst.hunger_tick = TUNING.SLEEP_HUNGER_PER_TICK
    --inst.is_cooling = false

    --inst.components.finiteuses:SetMaxUses(TUNING.TENT_USES)
    --inst.components.finiteuses:SetUses(TUNING.TENT_USES)

    return inst
end

return Prefab("mermhouse_player", fn, assets, prefabs),
	MakePlacer("mermhouse_placer", "mermhouse_player", "mermhouse_player", "idle")
