--Here we list any assets required by our prefab.
local assets=
{
    --this is the name of the Spriter file.
    Asset("ANIM", "anim/hooh.zip"),
	
	    --This is the FMOD file which contains all of the sound events.
    Asset("SOUNDPACKAGE", "sound/hooh.fev"),

    --This is the FMOD file which contains all the actual sound data.
    Asset("SOUND", "sound/hooh.fsb"),  
    
}

local prefabs=
{
	"rainbowfeather",
	"meat",
	"drumstick",
}

local loot = {
	"drumstick", "drumstick",
	"meat",
	"rainbowfeather", "rainbowfeather",
}


local WAKE_TO_FOLLOW_DISTANCE = 10
local SLEEP_NEAR_LEADER_DISTANCE = 7



local function EnableFlap(inst, enable)
    if enable then
        if not inst.flapping then
            inst.flapping = true
            if not inst:IsAsleep() then
                inst.SoundEmitter:PlaySound("hooh/hooh/wings", "flap")
            end
        end
    elseif inst.flapping then
        inst.flapping = false
        inst.SoundEmitter:KillSound("flap")
    end
end

local function tornadoimmunity(inst, amount, overtime, cause, ignore_invincible, afflicter, ignore_absorb)
    return afflicter ~= nil and (afflicter:HasTag("tornado")) --change the tag to whatever the tornado has.
end

local function RetargetFn(inst)
    return not inst.components.sleeper:IsAsleep()
        and (   FindEntity(
                    inst,
                    10,
                    function(guy)
                        return guy.components.combat.target == inst
                            and inst.components.combat:CanTarget(guy)
                    end,
                    { "_combat" }, --see entityreplica.lua
                    { "prey", "smallcreature", "INLIMBO" }
                )
            )
        or nil
end

local function KeepTargetFn(inst, target)
    return inst.components.combat:CanTarget(target)
end

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

local function OnHitOther(inst, target)

end

local function SetSpringBirdState(inst)
    inst:RemoveTag("companion")
    inst.components.hunger:SetKillRate(0)
end

local function StartSpringSmallBird(inst, leader)
    SetSpringBirdState(inst)
    inst.leader = leader
    inst.Transform:SetPosition(leader.Transform:GetWorldPosition())
end

local function onsave(inst, data)
    data.springbird = not inst:HasTag("companion") or nil
end

local function onload(inst, data)
    if data ~= nil and data.springbird then
        SetSpringBirdState(inst)
    end
end

local function ShouldWakeUp(inst)
    return DefaultWakeTest(inst) or not inst.components.follower:IsNearLeader(WAKE_TO_FOLLOW_DISTANCE)
end

local function ShouldSleep(inst)
    return DefaultSleepTest(inst) and inst.components.follower:IsNearLeader(SLEEP_NEAR_LEADER_DISTANCE)
end

local function FollowLeader(inst)
    local leader = inst.leader
    if leader == nil or not leader:IsValid() then
        inst.leader = nil
        if not inst:HasTag("companion") then
            --Spring birds just become orphans
            return
        end
        local x, y, z = inst.Transform:GetWorldPosition()
        leader = FindClosestPlayerInRange(x, y, z, 10, true)
        if leader == nil then
            --Didn't find a new parent yet
            return
        end
    end
    if leader.components.leader ~= nil then
        --print("   adding follower")
        leader.components.leader:AddFollower(inst)
        --[[if leader.components.homeseeker and leader.components.homeseeker:HasHome() and leader.components.homeseeker.home.prefab == "tallbirdnest" then 
            leader.components.homeseeker.home.canspawnsmallbird = true
        end]]
    end
end

local function OnAttacked(inst, data)
    inst.components.combat:SuggestTarget(data.attacker)
    inst.components.combat:ShareTarget(data.attacker, 10, function(dude) return dude:HasTag("hooh") and not dude.components.health:IsDead() end, 5)
end



--This function creates a new entity based on a prefab.
local function init_prefab()
	
    --First we create an entity.
    local inst = CreateEntity()

    --Then we add a transform component se we can place this entity in the world.
    local trans = inst.entity:AddTransform()

    --Then we add an animation component which allows us to animate our entity.
    local anim = inst.entity:AddAnimState()
	
	inst.entity:AddDynamicShadow()
    inst.entity:AddNetwork()
    
    --The bank name is the name of the Spriter file.
    anim:SetBank("hooh")

    --The build name is the name of the animation folder in spriter.
    anim:SetBuild("hooh")

    --We need to add a 'locomotor' component otherwise our creature can't walk around the world.
    inst:AddComponent("locomotor")

    --Here we can tune how fast our creature runs forward.
    inst.components.locomotor.runspeed = 3

    --We need to add a 'physics' component for our character to walk through the world.  Lucky for us, this
    --this is made easy for us by the 'MakeCharacterPhysics' function.  This function sets up physics,
    --collision tags, collision masks, friction etc.  All we need to give it is a mass and a radius which 
    --in this case we've set to 10 and 0.5.
    inst.Transform:SetScale(1, 1, 1)
    MakeCharacterPhysics(inst, 10, .25)
    inst.Transform:SetFourFaced()
		
    inst:AddTag("epic")
    inst:AddTag("noepicmusic")
    inst:AddTag("scarytoprey")
    inst:AddTag("flying")
	inst:AddTag("bird")
    inst:AddTag("companion")
    inst:AddTag("character")

    inst.flapping = true
    inst.EnableFlap = EnableFlap
	
	inst.entity:AddLight()
	inst.Light:Enable(true)
    inst.Light:SetRadius(5)
    inst.Light:SetFalloff(0.5)
    inst.Light:SetIntensity(0.75)
    inst.Light:SetColour(255/255, 182/255, 0/255)
    --Here we attach our stategraph to our prefab.
    inst:SetStateGraph("SGbabyhooh")
	
	inst.entity:AddSoundEmitter()
	inst.SoundEmitter:PlaySound("hooh/hooh/wings", "flap")
	
	inst.entity:SetPristine()
	
	if not TheWorld.ismastersim then
        return inst
    end
	
    --We need a reference to the brain we want to attach to our creature.
    local brain = require "brains/babyhoohbrain"

    --And then we attach the brain to our creature.
    inst:SetBrain(brain)
	
    inst.userfunctions =
    {
        FollowLeader = FollowLeader,
    }

    inst:AddComponent("follower")
    inst:AddComponent("lootdropper")
    inst:AddComponent("health")
	inst.components.health:SetMaxHealth(500)
    inst.components.health.fire_damage_scale = 0
	inst:AddComponent("inspectable")
	inst.components.health.redirect = tornadoimmunity
	
    inst:ListenForEvent("attacked", OnAttacked)
	
	inst:AddComponent("combat")
    inst:AddComponent("sleeper")	
	inst.components.sleeper:SetResistance(2)
    inst.components.combat:SetDefaultDamage(10)
    inst.components.combat:SetRange(5, 10)
    inst.components.lootdropper:SetLoot(loot)
	inst.components.combat.onhitotherfn = OnHitOther
	
    MakeHugeFreezableCharacter(inst)
    inst.components.freezable:SetResistance(TUNING.DRAGONFLY_FREEZE_THRESHOLD)
    inst.components.freezable.damagetobreak = TUNING.DRAGONFLY_FREEZE_RESIST
    inst.components.freezable.diminishingreturns = true
	
	
    --return our new entity so that it can be added to the world.
    return inst
end

--Here we register our new prefab so that it can be used in game.
return Prefab( "babyhooh", init_prefab, assets, nil)

