----------------------------------------------------------------------------
--  File          : /mods/4DC_V0.8/lua/4D_CloakRedirect/4D_CloakRedirect.lua 
-- 
--  Author        : Resin_Smoker 
-- 
--  Summary       : 4D_SDR: Allows a structure so enhanced to resist enemy fire. 
-- 
--   Special Thanks: Mithy for his redirect script

--  Copyright © 2011 4DC_V0.8  All rights reserved.
----------------------------------------------------------------------------
-- 
--  The following is required in the units script for Struture Damage Resistance (SDR)
--  This calls into action the SDR scripts for AStructureUnit 
-- 
--  local CAirUnit = import('/lua/cybranunits.lua').CAirUnit
--  CAirUnit = import('/mods/4DC_V0.8/lua/CustomAbilities/4D_CloakRedirect/4D_CloakRedirect.lua').CloakRedirect( CAirUnit )
--  
----------------------------------------------------------------------------

### Start of CloakRedirect(SuperClass) ###
function CloakRedirect(SuperClass) 
    return Class(SuperClass) {
    
    OnCollisionCheck = function(self, other, firingWeapon)
        -- Cloaking allows 50% chance to avoid anti-air missiles
        if not self:IsDead() and self.StealthEnabled then
            if ( other:GetBlueprint().Physics.TrackTarget or EntityCategoryContains(categories.MISSILE, other) ) and Random(1, 2) == 1 then                   
                if other:GetLauncher() then
                    -- Projectile returns to launcher
                    other:SetNewTarget(other:GetLauncher()) 
                    other:TrackTarget(true)
                    other.DamageData.CollideFriendly = true         
			        other.DamageData.DamageFriendly = true 
			        other.DamageData.DamageSelf = true 
			        other:SetLifetime(10)
	                other.Redirector = self
                    -- *** Mithy's Function *** Hook projectile's DoDamage to set (living) redirector to instigator on impact
                    local prevDoDamage = other.DoDamage
                    other.DoDamage = function(self, instigator, damageData, targetEntity)
                        --This should always allow the projectile to damage its launcher
                        instigator = self.Redirector or self
                        prevDoDamage(self, instigator, damageData, targetEntity)
                    end		        
                else
                    -- Projectile passes thru and losses tracking
                    other:TrackTarget(false)
                end
                return false  
            else               
                -- Projectile impacts normally
                return true 
            end
        end
        return SuperClass.OnCollisionCheck(self, other, firingWeapon) 
    end,             
}
end 
### End of CloakRedirect(SuperClass) ###