require "behaviours/follow"
require "behaviours/chaseandattack"
require "behaviours/runaway"
require "behaviours/wander"
require "behaviours/doaction"
require "behaviours/avoidlight"
require "behaviours/panic"

local FortressBrain = Class(Brain, function(self, inst)
    Brain._ctor(self, inst)
end)

local function GetTraderFn(inst)
    if inst.components.trader then
        return FindEntity(inst, TRADE_DIST, function(target) return inst.components.trader:IsTryingToTradeWithMe(target) end, {"player"})
    end
end

local function KeepTraderFn(inst, target)
    if inst.components.trader then
        return inst.components.trader:IsTryingToTradeWithMe(target)
    end
end

local function GetFaceTargetFn(inst)
    return inst.components.follower.leader
end

local function KeepFaceTargetFn(inst, target)
    return inst.components.follower.leader == target
end

function FortressBrain:OnStart()
    local root = PriorityNode(
        {
			ChaseAndAttack(self.inst, 20),
            Follow(self.inst, function() return self.inst.components.follower.leader end, 2, 5, 9),
            IfNode(function() return self.inst.components.follower.leader ~= nil end, "HasLeader",
				FaceEntity(self.inst, GetFaceTargetFn, KeepFaceTargetFn )),
            FaceEntity(self.inst, GetTraderFn, KeepTraderFn),
            Wander(self.inst, function() return self.inst.components.knownlocations:GetLocation("home") end, 20)            
	}, .25)
    
    self.bt = BT(self.inst, root)
end

return FortressBrain
