local assets =
{
    Asset("ANIM", "anim/fruitbat.zip"),
    Asset("SOUND", "sound/bat.fsb"),
}

local prefabs =
{
    "batwing",
	"cherry",
	"cherrygem",
}

local brain = require "brains/fruitbatbrain"

SetSharedLootTable( 'fruitbat',
{
    {'batwing',		0.15},
	{'cherry', 		0.80},
})

local SLEEP_DIST_FROMHOME = 1
local SLEEP_DIST_FROMTHREAT = 20

local function OnSleepGoHome(inst)
    inst._hometask = nil
    local home = inst.components.homeseeker ~= nil and inst.components.homeseeker.home or nil
    if home ~= nil and home:IsValid() and home.components.childspawner ~= nil then
        home.components.childspawner:GoHome(inst)
    end
end

local function OnIsDay(inst, isday)
    if isday then
		inst.Light:Enable(false)
        if inst._hometask == nil then
            inst._hometask = inst:DoTaskInTime(3 + math.random(), OnSleepGoHome)
        end
    elseif inst._hometask ~= nil then
        inst._hometask:Cancel()
        inst._hometask = nil
    end
end

local function StopWatchingDay(inst)
    inst:StopWatchingWorldState("isday", OnIsDay)
	inst.Light:Enable(true)
    if inst._hometask ~= nil then
        inst._hometask:Cancel()
        inst._hometask = nil
    end
end

local function StartWatchingDay(inst)
    inst:WatchWorldState("isday", OnIsDay)
    OnIsDay(inst, TheWorld.state.isday)
end

local function OnPreLoad(inst, data)
	local x, y, z = inst.Transform:GetWorldPosition()
	if y > 0 then
		inst.Transform:SetPosition(x, 0, z)
	end
end

local function ShouldAcceptItem(inst, item)
    return item.components.edible ~= nil and item.components.edible.foodtype == FOODTYPE.VEGGIE
end

local function OnGetItemFromPlayer(inst, giver, item)
    if item.components.edible ~= nil and item.components.edible.foodtype == FOODTYPE.VEGGIE then
        if inst.components.combat:TargetIs(giver) then
            inst.components.combat:SetTarget(nil)
        elseif giver.components.leader ~= nil then
            giver:PushEvent("makefriend")
            giver.components.leader:AddFollower(inst)
            inst.components.follower:AddLoyaltyTime(
                giver:HasTag("polite")
                and TUNING.ROCKY_LOYALTY + TUNING.ROCKY_POLITENESS_LOYALTY_BONUS
                or TUNING.ROCKY_LOYALTY
            )
            inst.sg:GoToState("eat_enter")
        end
    end
end

local function OnEat(inst, food)
    if  math.random() < 0.3 and food.components.edible ~= nil then
        if food.components.edible.foodtype == FOODTYPE.VEGGIE then
            SpawnPrefab("cherrygem").Transform:SetPosition(inst.Transform:GetWorldPosition())
        end
    end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddSoundEmitter()
    inst.entity:AddDynamicShadow()
	inst.entity:AddLight()
    inst.entity:AddNetwork()

    MakeGhostPhysics(inst, 1, .5)

    inst.DynamicShadow:SetSize(2.5, .75)

    inst.Transform:SetFourFaced()
    inst.Transform:SetScale(.75, .75, .75)

    inst.AnimState:SetBank("fruitbat")
    inst.AnimState:SetBuild("fruitbat")
	inst.AnimState:PlayAnimation("fly_loop", true)

    inst:AddTag("cavedweller")
	inst:AddTag("animal")
    inst:AddTag("bat")
    inst:AddTag("flying")
	inst:AddTag("trader")

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("locomotor")
    inst.components.locomotor:EnableGroundSpeedMultiplier(false)
    inst.components.locomotor:SetTriggersCreep(false)
    inst.components.locomotor.walkspeed = 8

    inst:SetStateGraph("SGfruitbat")
    inst:SetBrain(brain)

    inst:AddComponent("eater")
    inst.components.eater:SetDiet({ FOODTYPE.VEGGIE }, { FOODTYPE.VEGGIE })
    inst.components.eater.strongstomach = true
	inst.components.eater:SetOnEatFn(OnEat)
	
	inst:AddComponent("follower")
    inst.components.follower.maxfollowtime = TUNING.PIG_LOYALTY_MAXTIME
	
	inst:AddComponent("trader")
	inst.components.trader:SetAcceptTest(ShouldAcceptItem)
	inst.components.trader.onaccept = OnGetItemFromPlayer
	inst.components.trader.deleteitemonaccept = false

	inst.Light:SetRadius(1)
	inst.Light:SetFalloff(0.9)
	inst.Light:SetIntensity(0.5)
	inst.Light:SetColour(204/255, 92/255, 155/255)

    inst:AddComponent("combat")

    inst:AddComponent("health")
    inst.components.health:SetMaxHealth(100)

    inst:AddComponent("lootdropper")
    inst.components.lootdropper:SetChanceLootTable('fruitbat')

    inst:AddComponent("inventory")

    inst:AddComponent("inspectable")

    inst:AddComponent("knownlocations")

    MakeHauntablePanic(inst)

    inst.OnPreLoad = OnPreLoad

    return inst
end

return Prefab("fruitbat", fn, assets, prefabs)
