require "brains/shadowfriendbrain"
require "stategraphs/SGshadowcreature"

local prefabs =
{
    "nightmarefuel",
}

SetSharedLootTable( 'shadow_creature',
{
    {'nightmarefuel',  1.0},
})

local function OnAttacked(inst, data)
    inst.components.combat:SetTarget(data.attacker)
end

local function onsave(inst, data)
    data.timeleft = (inst.lifetime - inst:GetTimeAlive())
	data.build = inst.build
end

local function onload(inst, data)
    if data.timeleft then
        inst.lifetime = data.timeleft
        if inst.lifetime > 0 then
            resume(inst, inst.lifetime)
        else
            die(inst)
        end
    end
	
	if data then
		inst.build = data.build or builds[1]
			inst.AnimState:SetBuild(inst.build)
	end
end

local function KeepTarget(isnt, target)
    return target and target:IsValid()
end
		
local function entitydeathfn(inst, data)
    if data.inst:HasTag("player") then
        inst:DoTaskInTime(math.random(), function() inst.components.health:Kill() end)
    end
end

local function FollowPlayer(inst)
	local player = GetPlayer()
	if player and player.components.leader then
		player.components.leader:AddFollower(inst)
	end
end

local function die(inst)
	inst.components.health:Kill()
end

local function MakeShadowCreature(data)

    local bank = data.bank 
    local build = data.build 
    
    local assets=
    {
	    Asset("ANIM", "anim/"..data.build..".zip"),
    }
    
    local sounds = 
    {
        attack = "dontstarve/sanity/creature"..data.num.."/attack",
        attack_grunt = "dontstarve/sanity/creature"..data.num.."/attack_grunt",
        death = "dontstarve/sanity/creature"..data.num.."/die",
        idle = "dontstarve/sanity/creature"..data.num.."/idle",
        taunt = "dontstarve/sanity/creature"..data.num.."/taunt",
        appear = "dontstarve/sanity/creature"..data.num.."/appear",
        disappear = "dontstarve/sanity/creature"..data.num.."/dissappear",
    }

    local function fn()
	    local inst = CreateEntity()
	    local trans = inst.entity:AddTransform()
	    local anim = inst.entity:AddAnimState()
        local physics = inst.entity:AddPhysics()
	    local sound = inst.entity:AddSoundEmitter()
        inst.Transform:SetFourFaced()
    	
        MakeCharacterPhysics(inst, 10, 1.5)
        RemovePhysicsColliders(inst)
	    inst.Physics:SetCollisionGroup(COLLISION.SANITY)
	    inst.Physics:CollidesWith(COLLISION.SANITY)
	    --inst.Physics:CollidesWith(COLLISION.WORLD)
           
        anim:SetBank(bank)
        anim:SetBuild(build)
        anim:PlayAnimation("idle_loop")
        anim:SetMultColour(1, 1, 1, 0.5)
        inst:AddComponent("locomotor") -- locomotor must be constructed before the stategraph
        inst.components.locomotor.walkspeed = data.speed
        inst.sounds = sounds
        inst:SetStateGraph("SGshadowcreature")

        inst:AddTag("notraptrigger")
		inst:AddTag("companion")	
		inst:AddTag("hallucination")

        local brain = require "brains/shadowfriendbrain"
        inst:SetBrain(brain)
        
	    inst:AddComponent("sanityaura")
		inst.components.sanityaura.aura = (TUNING.SANITYAURA_TINY)
        
        inst:AddComponent("health")
        inst.components.health:SetMaxHealth(data.health)
		inst.components.health:StartRegen(2, 1)
		
        inst:AddComponent("combat")
        inst.components.combat:SetDefaultDamage(data.damage)
        inst.components.combat:SetAttackPeriod(data.attackperiod)
		inst.components.combat:SetKeepTargetFunction(KeepTarget)
		
		inst:AddComponent("follower")
		FollowPlayer(inst)
		
		inst.lifetime = (TUNING.SHADOWWAXWELL_LIFETIME * 3)
		inst.death = inst:DoTaskInTime(inst.lifetime, die)

        inst:AddComponent("lootdropper")
        inst.components.lootdropper:SetChanceLootTable('shadow_creature')
        
        inst:ListenForEvent("attacked", OnAttacked)
		inst:ListenForEvent("entity_death", function(world, data) entitydeathfn(inst, data) end, GetWorld())

        return inst
    end
        
    return Prefab("monsters/"..data.name, fn, assets, prefabs)
end


local data = {{name="crawlingbuddy", build = "shadow_insanity1_basic", bank = "shadowcreature1", num = 1, speed = (TUNING.CRAWLINGHORROR_SPEED*2), health=TUNING.CRAWLINGHORROR_HEALTH, damage=TUNING.TERRORBEAK_DAMAGE, attackperiod = TUNING.CRAWLINGHORROR_ATTACK_PERIOD},
			  {name="terrorfriend", build = "shadow_insanity2_basic", bank = "shadowcreature2", num = 2, speed = (TUNING.TERRORBEAK_SPEED*2), health=TUNING.TERRORBEAK_HEALTH, damage=30, attackperiod = TUNING.TERRORBEAK_ATTACK_PERIOD}}

local ret = {}
for k,v in pairs(data) do
	table.insert(ret, MakeShadowCreature(v))
end


return unpack(ret) 
