require "behaviours/follow"
require "behaviours/panic"
require "behaviours/standstill"
require "behaviours/chaseandattack"
require "behaviours/leash"
require "behaviours/wander"
require "behaviours/faceentity"
require "behaviours/runaway"
require "behaviours/doaction"
require "behaviours/findlight"
require "behaviours/chattynode"

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

local START_FACE_DIST = 20
local KEEP_FACE_DIST = 20

local MIN_FOLLOW_DIST = 2
local TARGET_FOLLOW_DIST = 5
local MAX_FOLLOW_DIST = 9

local MAX_WANDER_DIST = 20

local MAX_WANDER_DIST = 5

local MAX_CHASE_TIME = 10
local MAX_CHASE_DIST = 30

local RUN_AWAY_DIST = 2
local STOP_RUN_AWAY_DIST = 4


local function GetFaceTargetFn(inst)
    local target = GetClosestInstWithTag("player", inst, START_FACE_DIST)
    if target and not target:HasTag("notarget") then
        return inst.components.follower.leader
    end
end

local function KeepFaceTargetFn(inst, target)
    return inst.components.follower.leader == target and not target:HasTag("notarget")
end

local function GetLeader(inst)
    return inst.components.follower and inst.components.follower.leader
end

function RedDrakeBrain:OnStart()
    local root = 
    PriorityNode(
    {
            
            WhileNode(function() return self.inst.components.health.takingfiredamage end, "OnFire",
			
				ChattyNode(self.inst, STRINGS.REDDRAKE_TALK_PANICFIRE,
					Panic(self.inst))),
					
            ChattyNode(self.inst, STRINGS.REDDRAKE_TALK_FIGHT,
                WhileNode( function() return self.inst.components.combat.target == nil or not self.inst.components.combat:InCooldown() end, "AttackMomentarily",
                    ChaseAndAttack(self.inst, MAX_CHASE_TIME, MAX_CHASE_DIST) )),
					
            ChattyNode(self.inst, STRINGS.REDDRAKE_TALK_FIGHT,
                WhileNode( function() return self.inst.components.combat.target and self.inst.components.combat:InCooldown() end, "Dodge",
                    RunAway(self.inst, function() return self.inst.components.combat.target end, RUN_AWAY_DIST, STOP_RUN_AWAY_DIST) )),
                    RunAway(self.inst, function(guy) return guy.components.combat and guy.components.combat.target == self.inst end, RUN_AWAY_DIST, STOP_RUN_AWAY_DIST ),
			
            Follow(self.inst, function() return self.inst.components.follower.leader end, MIN_FOLLOW_DIST, TARGET_FOLLOW_DIST, MAX_FOLLOW_DIST),
                FaceEntity(self.inst, GetFaceTargetFn, KeepFaceTargetFn),
        }, .5)
		
    self.bt = BT(self.inst, root)
end

function RedDrakeBrain:OnInitializationComplete()
    --self.inst.components.knownlocations:RememberLocation("spawnpoint", Point(self.inst.Transform:GetWorldPosition()))
end

return RedDrakeBrain