require "behaviours/follow"
require "behaviours/wander"
require "behaviours/faceentity"
require "behaviours/panic"


local MIN_FOLLOW_DIST = 0
local MAX_FOLLOW_DIST = 12
local TARGET_FOLLOW_DIST = 6
local MAX_CHASE_TIME = 5
local MAX_WANDER_DIST = 3
local RUN_START_DIST = 3
local RUN_STOP_DIST = 8
local SEE_DIST = 30
local TOOCLOSE = 10

local function StealAction(inst)
    if not inst.components.container:IsFull() then
		local player = GetPlayer()
		local target = FindEntity(inst, SEE_DIST, function(item) 
			if item.components.inventoryitem and 
				item.components.inventoryitem.canbepickedup and 
				not item.components.inventoryitem:IsHeld() and
				item:IsOnValidGround() and 
				not item:HasTag("irreplaceable") and
				not item:HasTag("prey") and
				not item.prefab == "firebox" and
				not item.prefab == "firebag" and
				not item.prefab == "firesword" and
				not item.prefab == "firearmor" and
				not item.prefab == "firehelm" and
				not item.prefab == "backpack" and
				not item.prefab == "piggyback" and
				not item.prefab == "krampus_sack" and
				not item:HasTag("bird") then
				
					return player and player:GetDistanceSqToInst(item) < TOOCLOSE*TOOCLOSE

				end
			end)

		if target then
			return BufferedAction(inst, target, ACTIONS.PICKUP)
		end
 
	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 KrampuserBrain = Class(Brain, function(self, inst)
    Brain._ctor(self, inst)
end)


function KrampuserBrain:OnStart()
    local stealnode = PriorityNode(
	{
		DoAction(self.inst, function() return StealAction(self.inst) end, "steal", true ),        
	}, 2)
    local root = 
    PriorityNode({
        --WhileNode( function() return self.inst.components.health.takingfiredamage end, "OnFire", Panic(self.inst)),
        ChaseAndAttack(self.inst, MAX_CHASE_TIME),

		MinPeriod(self.inst, 1, 
			stealnode),

        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),
        Wander(self.inst, function() return self.inst.components.knownlocations:GetLocation("home") end, MAX_WANDER_DIST),
        
    }, .25)
    self.bt = BT(self.inst, root)
end

return KrampuserBrain