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 == GetPlayer() or data.target:HasTag("companion") or data.target:HasTag("imoogi") or inst:HasTag("stay")) then
	inst.components.combat:GiveUp() return end
	if inst:HasTag("stay") then
	inst.components.combat:GiveUp() return end
	
end

local function OnAttacked(inst, data)
    local attacker = data and data.attacker
    if attacker == GetPlayer() then
	inst.components.combat:GiveUp()
    return end
	if inst:HasTag("stay") then return end
    inst.components.combat:SetTarget(attacker)
    inst.components.combat:ShareTarget(attacker, 15, function(dude) return dude:HasTag("companion") and not dude:HasTag("stay") end, 10)
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 FollowPlayer(inst)
local player = GetPlayer()
if not inst:HasTag("stay") then
	if player and player.components.leader then
		player.components.leader:AddFollower(inst)
	end
elseif inst:HasTag("stay") then
	inst.components.follower:SetLeader(nil)
end
end

local function KeepTarget(inst, target)
local player = GetPlayer()
    if not inst.components.health:IsDead() and (player:HasTag("callpet") or inst:HasTag("stay")) then
	 inst.components.combat:GiveUp()
	 inst.components.combat:SetTarget(nil)
	 return
	elseif not inst.components.health:IsDead() and not (player:HasTag("callpet") or inst:HasTag("stay")) then
	 return inst.components.combat:CanTarget(target) and ((not inst:HasTag("companion") or not inst:HasTag("stay")) or inst:IsNear(target, 20))
	end
end

local function GetSmallGrowTime(inst)
	return TUNING.SMALLBIRD_GROW_TIME
end

local function SetMir2(inst)
if not inst:HasTag("growstop") then
	inst.sg:GoToState("growup")
end
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("imoogi")
	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()
	if IsDLCEnabled(CAPY_DLC) then
		MakeAmphibiousCharacterPhysics(inst, 75, .5)
	else
	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)
	end
    inst.Transform:SetFourFaced()	

    inst.userfunctions = 
    {
        FollowPlayer = FollowPlayer,
        SpawnMir2 = SpawnMir2,
        --SpawnMir3 = SpawnMir3,
    }
	
    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()
	
	inst:DoTaskInTime(1, function(inst)
        if not TheSim:FindFirstEntityWithTag("player") then
            inst:Remove()
        end
    end)

    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 = 7
	
    inst.components.combat:SetDefaultDamage(30)

    inst.components.health:SetMaxHealth(500)
	inst.components.health:StartRegen(1, 10)

    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 = 7
	
    inst.components.combat:SetDefaultDamage(50)

    inst.components.health:SetMaxHealth(600)
	inst.components.health:StartRegen(2, 10)

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

	return inst
end


STRINGS.NAMES.MIR = "Imoogi"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.MIR = "Tiny Orient Dragon.\nSo cute!"

STRINGS.NAMES.MIR2 = "Imoogi"
STRINGS.CHARACTERS.GENERIC.DESCRIBE.MIR2 = "Tiny Orient Dragon."

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