----------------------------------------------------------------------------- 
--  File          : /lua/4D_Crush.lua 
-- 
--  Author        : Resin_Smoker 
-- 
--  Summary       : Allows a unit to crush smaller units it rolls over
-- 
--  Copyright © 2011 4DC_V0.8  All rights reserved.
----------------------------------------------------------------------------- 
-- 
--  The following is required in the units script for CRUSH
--  This calls into action the Crush scripts for TLandUnit 
-- 
--  local TLandUnit = import('/lua/terranunits.lua').TLandUnit
--  TLandUnit = import('/mods/4DC_V0.8/lua/CustomAbilities/4D_Crush/4D_Crush.lua').Crush( TLandUnit )
--
--   The following is optional in the units script to set the radius and amount of Crush
--   
--   OnCreate = function(self,builder,layer)
--       TLandUnit.OnCreate(self)     
--       self.CrushRadius = 1.5
--       self.CrushDMG = 50
--   end, 
-- 
-----------------------------------------------------------------------------
local utilities = import('/lua/Utilities.lua')

### Start of Crush(SuperClass) ###
function Crush(SuperClass) 
    return Class(SuperClass) {
    
    OnStopBeingBuilt = function(self,builder,layer)
        SuperClass.OnStopBeingBuilt(self,builder,layer)
        self.Moving = false
        self.CrushHeartBeat = false
    end, 
    
    HeartBeatCrushCheck = function(self)
        -- Checks to see if the unit is moving and if so apply damage to enemy units near it    
        while self and not self:IsDead() and self.Moving == true do
            self.CrushHeartBeat = true
            -- Search for enemy units nearby
            local targetlist = utilities.GetEnemyUnitsInSphere(self, self:GetPosition(), (self.CrushRadius or 1 ) )
            if table.getsize (targetlist) > 0 then
                -- Apply damage
                DamageArea(self, self:GetPosition(), (self.CrushRadius or 1 ), (self.CrushDMG or 10 ), 'Force', false, false)
            end
            WaitSeconds(self.CrushDelay or 1)            
        end
        self.CrushHeartBeat = false
    end,
    
   OnMotionHorzEventChange = function(self, new, old)
       -- Updates the gloabal variable for when the units movement changes
       if self and not self:IsDead() then        
           if new == 'Stopped' then
               self.Moving = false
           else
               self.Moving = true
               if not self.CrushHeartBeat then
                   self:ForkThread(self.HeartBeatCrushCheck)
               end
           end
       end              
       SuperClass.OnMotionHorzEventChange(self, new, old)
   end,             
     
}
end 
### End of Crush(SuperClass) ###