require "prefabutil"

local assets =
{
    
}

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

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

local MIN_HEAT = 99
local MAX_HEAT = 100

SetSharedLootTable('hound_moundp',
{
    {'houndstooth', 1.00},
    {'houndstooth', 1.00},
    {'houndstooth', 1.00},
    {'boneshard',   1.00},
    {'boneshard',   1.00},
    {'redgem',      0.01},
    {'bluegem',     0.01},
})

local loot =
{
	"houndstooth",
	"houndstooth",
	"houndstooth",
	"boneshard",
	"boneshard",
}

local function GetSpecialHoundChance()
    local day = TheWorld.state.cycles
    local chance = 0
    for k, v in ipairs(TUNING.HOUND_SPECIAL_CHANCE) do
        if day <= v.minday then
            return chance
        end
        chance = v.chance
    end
    return chance
end

local function SpawnGuardHound(inst, attacker)
    local prefab =
        (math.random() >= GetSpecialHoundChance() and "hound") or
        ((TheWorld.state.iswinter or TheWorld.state.isspring) and "icehound") or
        "firehound"
    local defender = inst.components.childspawner:SpawnChild(attacker, prefab)
    if defender ~= nil and attacker ~= nil and defender.components.combat ~= nil then
        defender.components.combat:SetTarget(attacker)
        defender.components.combat:BlankOutAttacks(1.5 + math.random() * 2)
    end
end

local function SpawnGuards(inst)
    if not inst.components.health:IsDead() and inst.components.childspawner ~= nil then
        local num_to_release = math.min(3, inst.components.childspawner.childreninside)
        for k = 1, num_to_release do
            SpawnGuardHound(inst)
        end
    end
end

local function SpawnAllGuards(inst, attacker)
	inst.AnimState:PlayAnimation("hit")
    inst.AnimState:PushAnimation("idle", false)
    if not inst.components.health:IsDead() and inst.components.childspawner ~= nil then
        local num_to_release = inst.components.childspawner.childreninside
        for k = 1, num_to_release do
            SpawnGuardHound(inst)
        end
    end
end

local function OnIsSummer(inst, issummer)
    inst.components.childspawner:SetRareChild("firehound", issummer and 0.2 or 0)
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")
	if MOBHOUSE == "Enable1" or MOBHOUSE == "Disable" then
   -- inst.components.lootdropper:DropLoot()
	end
    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")
        inst.AnimState:PushAnimation("idle")
    end
end

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



local function OnEntityWake(inst)
	if MOBPVPMODE == "Enable" and inst.components.childspawner ~= nil then
	inst.components.childspawner:StartSpawning()
	end
    --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()
		if inst.rooms == 0 then
			inst.sleeptask = nil
		end	
    end
	
	inst.AnimState:PlayAnimation("hit")
	inst.SoundEmitter:KillSound("loop")
	
    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("idle", true)
    end

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

local function OnKilled(inst)
    inst.AnimState:PlayAnimation("death", false)
	inst.components.sleepingbag:DoWakeUp()
	if inst.components.childspawner ~= nil then
        inst.components.childspawner:ReleaseAllChildren()
    end
    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("hound") then
		 inst.SoundEmitter:KillSound("loop")
		 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()
		inst.SoundEmitter:KillSound("loop")
    end
end

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

    if inst.sleeptask ~= nil  then --if sleep test is not nil, then that means no one else can use it...
        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:AddGroundCreepEntity()
        inst.entity:AddSoundEmitter()
        inst.entity:AddMiniMapEntity()
        inst.entity:AddNetwork()

    MakeObstaclePhysics(inst, 0.5)

    inst.MiniMapEntity:SetIcon("hound_mound.png")
	
	inst.hunger_tick = 0
	
	MakeSnowCoveredPristine(inst)
	
	inst.AnimState:SetBank("houndbase")
    inst.AnimState:SetBuild("hound_base")
    inst.AnimState:PlayAnimation("idle")

        inst:AddTag("structure")
        inst:AddTag("chewable") -- by werebeaver
        inst:AddTag("houndhouse") -- prevents other mobs from sleeping in here.
        inst:AddTag("houndmound")
		inst:AddTag("shelter") -- this is to allow cooling during summer.
        inst:AddTag("hive")

		inst.mobhouse = true
	---------------------------------------
	---PvP Mode----------------------------
	if MOBPVPMODE == "Enable" then
    inst:AddComponent("childspawner")
    inst.components.childspawner.childname = "hound"
    inst.components.childspawner:SetRegenPeriod(TUNING.HOUNDMOUND_REGEN_TIME)
    inst.components.childspawner:SetSpawnPeriod(TUNING.HOUNDMOUND_RELEASE_TIME)
    inst.components.childspawner:SetMaxChildren(math.random(TUNING.HOUNDMOUND_HOUNDS_MIN, TUNING.HOUNDMOUND_HOUNDS_MAX))

    inst:WatchWorldState("issummer", OnIsSummer)
    OnIsSummer(inst, TheWorld.state.issummer)
	end
	---------------------------------------
	
	inst:AddComponent("heater") 
	inst.components.heater.heat = 40
		
    --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("combat")
    inst.components.combat:SetOnHit(SpawnAllGuards)
    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.HAMMER)
	--if MOBPVPMODE == "Enable" then
    --inst.components.workable:SetWorkLeft(6)
	--else
	--inst.components.workable:SetWorkLeft(3)
	--end
    --inst.components.workable:SetOnFinishCallback(onhammered)
    --inst.components.workable:SetOnWorkCallback(onhit)
	
    inst:AddComponent("lootdropper")
	--if MOBHOUSE == "Enable1" or MOBHOUSE == "Disable" then --this is to prevent conflicts with the crafting recipe, still doubles the loot for some reason.
		inst.components.lootdropper:SetChanceLootTable('hound_moundp')
	--end

    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("houndmound_p", MakeDenFn(), assets, prefabs),
	--Prefab("spidernest2_p", fn(2), assets, prefabs),
	--Prefab("spidernest3_p", fn(3), assets, prefabs),
	MakePlacer("houndmound_p_placer", "houndbase", "hound_base", "idle")
