require "behaviours/follow"
require "behaviours/wander"
require "behaviours/chaseandattack"
require "behaviours/runaway"

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

local MIN_FOLLOW = 8
local MAX_FOLLOW = 17
local MED_FOLLOW = 8
local MAX_WANDER_DIST = 12
local MAX_CHASE_TIME = 10

local MIN_FOLLOW_LEADER = 8
local MAX_FOLLOW_LEADER = 12
local RUN_START_DIST = 7
local RUN_STOP_DIST = 15

local KEEP_CHOPPING_DIST = 10
local SEE_TREE_DIST = 20

local function KeepChoppingAction(inst)
    return inst.components.follower.leader and inst.components.follower.leader:GetDistanceSqToInst(inst) <= KEEP_CHOPPING_DIST*KEEP_CHOPPING_DIST
end

local function StartChoppingCondition(inst)
    return inst.components.follower.leader and inst.components.follower.leader.sg and inst.components.follower.leader.sg:HasStateTag("chopping")
end

local function FindTreeToChopAction(inst)
    local target = FindEntity(inst, SEE_TREE_DIST, function(item) return item.components.workable and item.components.workable.action == ACTIONS.CHOP end)
    if target then
        return BufferedAction(inst, target, ACTIONS.CHOP)
    end
end

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

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

local function ShouldRunAway(guy)
    return not guy:HasTag("character") and not guy:HasTag("wormspider") and (guy:HasTag("character") or guy:HasTag("monster")) or guy:HasTag("beefalo") and not guy:HasTag("notarget")
end

local function CanAttackNow(inst)
    return inst.components.combat.target == nil or not inst.components.combat:InCooldown()
end

function FlyingwormBrain:OnStart()

    local root = PriorityNode(
    {
		IfNode(function() return StartChoppingCondition(self.inst), "chop", 
			KeepChoppingAction(self.inst) end, "keep chopping",
				DoAction(self.inst, FindTreeToChopAction)),
        WhileNode( function() return self.inst.components.combat.target == nil or not self.inst.components.combat:InCooldown() end, "AttackMomentarily",
            ChaseAndAttack(self.inst, MAX_CHASE_TIME)),
        WhileNode( function() return self.inst.components.combat.target and self.inst.components.combat:InCooldown() end, "Dodge",
			RunAway(self.inst, ShouldRunAway, RUN_START_DIST, RUN_STOP_DIST)),

		Follow(self.inst, function() return self.inst.components.follower.leader end, MIN_FOLLOW, MED_FOLLOW, MAX_FOLLOW, true),
		--FaceEntity(self.inst, GetFaceTargetFn, KeepFaceTargetFn),
        Wander(self.inst, function() return Point(GetPlayer().Transform:GetWorldPosition()) end , MAX_WANDER_DIST)        
    }, .5)
        
    self.bt = BT(self.inst, root)
         
end


return FlyingwormBrain