


local FairytaleBajie = Class(function(self, inst)

    self.inst = inst
	self.ismanmade = false
    self.active = false
	
	inst:ListenForEvent("bajie_normal", function(inst, data)
		
		if self.active then
		
			inst.components.locomotor.walkspeed = inst.components.locomotor.walkspeed / 2
			inst.components.locomotor.runspeed = inst.components.locomotor.runspeed / 2
			inst.components.combat.damagemultiplier = inst.components.combat.damagemultiplier / 2
			
			self:DisablePigmanFollow()
			
			self.active = false
		end
		
	end)
	
	inst:ListenForEvent("bajie_fairytale", function(inst, data)
	
		if not self.active then
		
			inst.components.locomotor.walkspeed = inst.components.locomotor.walkspeed * 2
			inst.components.locomotor.runspeed = inst.components.locomotor.runspeed * 2
			inst.components.combat.damagemultiplier = inst.components.combat.damagemultiplier * 2
			
			self:EnablePigmanFollow()
			
			self.active = true
		end
	end)
end)

function FairytaleBajie:OnSave()
    return { 
        active = self.active,
    } 
end



function FairytaleBajie:EnablePigmanFollow()

	
	local function pigman_update()
	
		-- Only update if player has spawned.
		local player = GetPlayer()
		if not player then
			return
		end

		-- Get all entities around the player which haven't already been tagged.
		local x,y,z = player.Transform:GetWorldPosition()
		local ignore_tags = {"pig"}
		local entities = TheSim:FindEntities(x,y,z, 20, {}, ignore_tags)
	
		player.components.leader:RemoveFollowersByTag("pig")
		local x,y,z = player.Transform:GetWorldPosition()
		local ents = TheSim:FindEntities(x,y,z, 20, {"pig"})
		for k,v in pairs(ents) do
			if v.components.follower and not v.components.follower.leader and not player.components.leader:IsFollower(v) and player.components.leader.numfollowers < 10 then
                    player.components.leader:AddFollower(v)
            end
		end
	end
	
	--pigman_update()
	self.updatetask = self.inst:DoTaskInTime(0.5, pigman_update)
	--self.inst.updatetask = GLOBAL.scheduler:ExecutePeriodic(0.5, pigman_update) --self.inst:DoPeriodcTask(0.5, pigman_update, 1)
	--self.inst.updatetask = self.inst:DoPeriodcTask(0.5, pigman_update, 1)
end

function FairytaleBajie:DisablePigmanFollow()
	if self.updatetask then
		self.updatetask:Cancel()
        self.updatetask = nil
    end
	
	local player = GetPlayer()
	
	if player and player.components.leader then
		player:RemoveTag("monster")
            for k,v in pairs(player.components.leader.followers) do
                if k:HasTag("spider") and k.components.combat then
                    k.components.combat:SuggestTarget(player)
                end
            end
		player.components.leader:RemoveFollowersByTag("spider")
	end
end
   
function FairytaleBajie:OnLoad(data)
    if data then
        self.active = data.active
	end
	-- debug
	--GetPlayer().components.components.hunger:SetPercent(1)
end
  
return FairytaleBajie