require "prefabutil"

local assets = 
{
	Asset("ANIM", "anim/mir.zip"),
	
	Asset( "SOUND" , "sound/mir.fsb" ),
	Asset( "SOUNDPACKAGE" , "sound/mir.fev" ),
}

local prefabs = {}

local WAKE_TO_FOLLOW_DISTANCE = 10
local SLEEP_NEAR_LEADER_DISTANCE = 7

local function OnSpawnFuel(inst, fuel)
	inst.sg:GoToState("idle", fuel)
	local fx = SpawnPrefab("collapse_small")
	fx.Transform:SetPosition(inst.Transform:GetWorldPosition())
end
local function OnNewTarget(inst, data)
    if data.target and data.target:HasTag("player") then
	return
	elseif inst:HasTag("stay") then
	inst.components.combat:SetTarget(nil)
end
end

local function OnAttacked(inst, data)
    local attacker = data and data.attacker
    if attacker == GetPlayer() then
    return
    else
    inst.components.combat:SetTarget(data.attacker)
    inst.components.combat:ShareTarget(data.attacker, 15, function(dude) return dude:HasTag("companion") and not dude:HasTag("stay") end, 10)
end
end

local function OnEat(inst, food)
	inst.components.health:DoDelta(10)
	inst.components.combat:SetTarget(nil)
	if math.random() < .1 and food and food.components.edible.foodtype == "MEAT" then
	local fx = SpawnPrefab("collapse_small")
	local item = {"rock","nitre"}
	local randomitem = item[math.random(#item)]
	local prank = SpawnPrefab(randomitem)
	fx.Transform:SetScale(.6,.6,.6)
	fx.Transform:SetPosition(inst.Transform:GetWorldPosition())
	prank.Transform:SetPosition(inst.Transform:GetWorldPosition())
end
end

local function OnRefuseItem(inst, item)
end
local function CanEatTest(inst, item)
    local canEat = (item.components.edible.foodtype == "MEAT")
    return canEat
end
local function ShouldAcceptItem(inst, item)
    if item.components.edible and inst.components.eater then
        return inst.components.eater:CanEat(item)
    end
end
local function OnGetItemFromPlayer(inst, giver, item)
    if inst.components.sleeper then
        inst.components.sleeper:WakeUp()
    end
    if item.components.edible then
        if inst.components.combat.target and inst.components.combat.target == giver then
            inst.components.combat:SetTarget(nil)
        end
        if inst.components.eater:Eat(item) then
		inst.sg:GoToState("eat")
        end
    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 OnNear(inst)
    --print("tallbirdegg - OnNear")
	local player = GetPlayer()
	player.components.leader:AddFollower(inst)

end

local function OnFar(inst)
    --print("tallbirdegg - OnFar")
    if inst:HasTag("stay") then
    inst.components.follower:SetLeader(nil)
    end
end

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

local function KeepTarget(inst, target)
local player = GetPlayer()
    if not inst.components.health:IsDead() and player:HasTag("callpet") and inst:HasTag("stay") then
	inst.components.combat:SetTarget(nil)
	return

    elseif not inst.components.health:IsDead() and not player:HasTag("callpet") then
    return inst.components.combat:CanTarget(target) and (not inst:HasTag("companion") or inst:IsNear(target, 20))
end
end

local function GetSmallGrowTime(inst)
	return TUNING.SMALLBIRD_GROW_TIME
end

local function SetMir2(inst)
    inst.sg:GoToState("growup")
end
local function SpawnMir2(inst)
    local mir2 = SpawnPrefab("mir2")
    mir2.Transform:SetPosition(inst.Transform:GetWorldPosition())
    mir2.sg:GoToState("growstop")
	local fx = SpawnPrefab("collapse_small")
	fx.Transform:SetPosition(inst.Transform:GetWorldPosition())
	
    if inst.components.follower.leader then
        mir2.components.follower:SetLeader(inst.components.follower.leader)
    end
    inst:Remove()
end

local function create_common(inst)
	inst:AddTag("mir")
	inst:AddTag("scarytoprey")
	inst:AddTag("noauradamage")
	inst:AddTag("notraptrigger")
    inst:AddTag("companion")
    inst:AddTag("character")
	
    inst.entity:AddMiniMapEntity()
	inst.MiniMapEntity:SetIcon( "mir.tex" )

	inst.entity:AddSoundEmitter()
	inst.entity:AddDynamicShadow()
	
	MakeCharacterPhysics(inst, 1, .25)
    
    inst.Physics:SetCollisionGroup(COLLISION.CHARACTERS)
    inst.Physics:ClearCollisionMask()
    inst.Physics:CollidesWith(COLLISION.WORLD)
    inst.Physics:CollidesWith(COLLISION.OBSTACLES)
    inst.Physics:CollidesWith(COLLISION.CHARACTERS)

    inst.Transform:SetFourFaced()	

    inst.userfunctions = 
    {
        FollowPlayer = FollowPlayer,
        SpawnMir2 = SpawnMir2,
        --SpawnMir3 = SpawnMir3,
    }
	
    inst:AddComponent("playerprox")
    inst.components.playerprox:SetDist(30, 30)
    inst.components.playerprox:SetOnPlayerNear(OnNear)
    inst.components.playerprox:SetOnPlayerFar(OnFar)
	
    inst:AddComponent("health")
	inst.components.health.fire_damage_scale = 0
	
    inst:AddComponent("knownlocations")
    MakeSmallBurnableCharacter(inst, "body")

    inst:AddComponent("combat")
    inst.components.combat:SetRange(2, 2.5)
    inst.components.combat:SetAttackPeriod(2)
	inst.components.combat:SetKeepTargetFunction(KeepTarget)
	inst.components.combat:SetHurtSound("mir/mir/hit")
	
	inst:ListenForEvent("attacked", OnAttacked)
    inst:ListenForEvent("newcombattarget", OnNewTarget)
--[[
    inst:AddComponent("eater")
    inst.components.eater:SetOmnivore()
    inst.components.eater:SetOnEatFn(OnEat)

    inst:AddComponent("trader")
    inst.components.trader:SetAcceptTest(ShouldAcceptItem)
    inst.components.trader.onaccept = OnGetItemFromPlayer
    inst.components.trader.onrefuse = OnRefuseItem
]]
    inst:AddComponent("inspectable")
    inst:AddComponent("locomotor")
	inst:AddComponent("lootdropper")
    inst:AddComponent("follower")
	inst:AddComponent("talker")
	inst.components.talker.font = TALKINGFONT
	
    inst:AddComponent("sleeper")
    inst.components.sleeper:SetResistance(3)
    inst.components.sleeper.testperiod = GetRandomWithVariance(6, 2)
    inst.components.sleeper:SetSleepTest(ShouldSleep)
    inst.components.sleeper:SetWakeTest(ShouldWakeUp)

    inst:AddComponent("mirspawner")
    inst.components.mirspawner:SetOnSpawnFn(OnSpawnFuel)
    inst.components.mirspawner.prefab = "goldnugget"
    inst.components.mirspawner.basetime = TUNING.TOTAL_DAY_TIME * 10
    inst.components.mirspawner.randtime = TUNING.TOTAL_DAY_TIME * 10
    inst.components.mirspawner:Start()

    if ACTIONS.PETSTAY ~= nil then
    	inst:AddComponent("petstay")
    end
	
	local brain = require "brains/mirbrain"
    inst:SetBrain(brain)
	
    return inst
end

local function create_mir()
	local inst = CreateEntity()
	local trans = inst.entity:AddTransform()
	local anim = inst.entity:AddAnimState()
	local sound = inst.entity:AddSoundEmitter()
	local shadow = inst.entity:AddDynamicShadow()
	shadow:SetSize(1.25, .75)
	inst.Transform:SetScale(.8,.8,.8)
	
	create_common(inst)
	inst:SetStateGraph("SGmir")

	anim:SetBank("mir")
	anim:SetBuild("mir")
	
	inst.components.lootdropper.numrandomloot = 1
	inst.components.lootdropper:AddRandomLoot("miregg", 1)

    inst.components.locomotor.walkspeed = 5
	
    inst.components.combat:SetDefaultDamage(20)

    inst.components.health:SetMaxHealth(200)
	inst.components.health:StartRegen(10, 6)

    inst.components.talker.fontsize = 20
    inst.components.talker.offset = Vector3(0,-400,0)

    local growth_stages = {
        {name="mir", time = GetSmallGrowTime, fn = function() end },
        {name="mir2", fn = SetMir2}
    }

	inst:AddComponent("growable")
    inst.components.growable.stages = growth_stages
    inst.components.growable:SetStage(1)
    inst.components.growable:StartGrowing()

	return inst
end

local function create_mir2()
	local inst = CreateEntity()
	local trans = inst.entity:AddTransform()
	local anim = inst.entity:AddAnimState()
	local sound = inst.entity:AddSoundEmitter()
	local shadow = inst.entity:AddDynamicShadow()
	shadow:SetSize(1.25, .75)
	inst.Transform:SetScale(1,1,1)
	
	create_common(inst)
	inst:SetStateGraph("SGmir2")

	anim:SetBank("mir")
	anim:SetBuild("mir")
	
	inst.components.lootdropper.numrandomloot = 1
	inst.components.lootdropper:AddRandomLoot("miregg", 1)

    inst.components.locomotor.walkspeed = 6
	
    inst.components.combat:SetDefaultDamage(100)

    inst.components.health:SetMaxHealth(999999999)
	inst.components.health:StartRegen(999999999, 1)

    inst.components.talker.fontsize = 23
    inst.components.talker.offset = Vector3(0,-350,0)

	return inst
end


STRINGS.NAMES.MIR = "Mir"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.MIR = "ÃÔÄãÁú.\nºÃ¿É°®!"

STRINGS.NAMES.MIR2 = "Mir"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.MIR2 = "ÃÔÄãÁú.\nºÃ¿É°®"

return Prefab( "common/mir", create_mir, assets, prefabs),
	      Prefab( "common/mir2", create_mir2, assets)