--[[
作者：小开心
请不要擅自修改或删除
请尊重版权
@

说明：
想患 懒癌强迫症
]]

return function( Grue )

    Grue.immunity = {}

    function Grue:AddImmunity(source)
        self.immunity[source or self] = true
        self:Stop()
    end

    function Grue:RemoveImmunity(source)
        self.immunity[source or self] = nil
        if next(self.immunity) == nil then
            self:Start()
        end
    end

    function Grue:CheckForStart()
        return not self.inst.components.health:IsInvincible() and 
            not self.inst.LightWatcher:IsInLight() and 
            not self.inst.components.health:IsDead() and 
            next(self.immunity) == nil
    end

    function Grue:Start()
        if self.level == nil and self:CheckForStart() then
            self.inst:StartUpdatingComponent(self) 
            self.nextHitTime = 5+math.random()*5
            self.nextSoundTime = self.nextHitTime* (.4 + math.random()*.4)
        end
    end

    function Grue:OnUpdate(dt)
        if self.inst.components.health:IsDead() or self.inst.components.health:IsInvincible() then
            self:Stop()
            return
        end
        
        if self.nextHitTime > 0 then
            self.nextHitTime = self.nextHitTime - dt
        end
        
        if self.nextSoundTime > 0 then
            self.nextSoundTime = self.nextSoundTime - dt
            
            if self.nextSoundTime <= 0 then
                if self.soundwarn then
                    self.inst.SoundEmitter:PlaySound(self.soundwarn)
                end
                self.inst:DoTaskInTime(self.warndelay, function() self.inst:PushEvent("heargrue") end)
            end
            
        end
        
        if self.nextHitTime <= 0 then
        
            self.nextHitTime = self.nextHitTime - dt
            self.nextSoundTime = self.nextSoundTime - dt
            self.inst.components.combat:GetAttacked(nil, TUNING.GRUEDAMAGE)
    		self.inst.components.sanity:DoDelta(-TUNING.SANITY_MEDLARGE)
            
            self.nextHitTime = 5+math.random()*6
            self.nextSoundTime = self.nextHitTime* (.4 + math.random()*.4)
            if self.soundattack then
                self.inst.SoundEmitter:PlaySound(self.soundattack)
            end
            
            self.inst:PushEvent("attackedbygrue")
        end
    end
end
