#
# Terran Anti Air Missile
#
local TMissileAAProjectile = import('/lua/terranprojectiles.lua').TMissileAAProjectile
EMESamHVM01 = Class(TMissileAAProjectile) {

    OnCreate = function(self)
        TMissileAAProjectile.OnCreate(self)
        self:SetCollisionShape('Sphere', 0, 0, 0, 1.2)
        self:ForkThread(self.Tracking)
    end,

    Tracking = function(self)
    	--local launcher = self:GetLauncher()
       -- local aiBrain = launcher:GetAIBrain()
        local target = self:GetTrackingTarget() 
        local position = self:GetPosition() 
        local targetlist
        self.range=80      
        --LOG("start Tracking")
        
        if target.IncommingDamage then
        	--LOG(target:GetHealth())
        	if target.IncommingDamage<target:GetHealth()*2 then
        		target.IncommingDamage=target.IncommingDamage+self.DamageData.DamageAmount
        	else
        		self:Retarget()
        		
        	end
        	
        else 
        	--LOG(self.DamageData.DamageAmount)
        	target.IncommingDamage=self.DamageData.DamageAmount
        end
        
        while not self:BeenDestroyed() do 
        	if target:IsDead() then
        		self:Retarget()   		
        	end
        	WaitSeconds(0.5)
        	self.range=self.range-10
        end
    end,
    
    Retarget = function(self)
    	--LOG("Retarget")
  	    local launcher = self:GetLauncher()
    	local aiBrain = launcher:GetAIBrain() 
    	local position = self:GetPosition()
    	local targetlist = aiBrain:GetUnitsAroundPoint( categories.AIR, position, self.range ,'ENEMY') 
        if targetlist[1] then
          	self:SetNewTarget(targetlist[1])
          	for k, v in targetlist do
          		if not v.IncommingDamage then
          			self:SetNewTarget(v)
          			v.IncommingDamage=self.DamageData.DamageAmount
          			break
          		else
          			if v.IncommingDamage<v:GetHealth()*2 then
        				self:SetNewTarget(v)	
          				v.IncommingDamage=v.IncommingDamage+self.DamageData.DamageAmount
          				break
        			end 
          		end
            --LOG(k)
            end
        else
          	self:Destroy() 
      	end  
    end,
    
    OnDestroy = function(self)
    	--LOG("Destroyed")
    	local target = self:GetTrackingTarget()
    	if target and target.IncommingDamage then
    		target.IncommingDamage=target.IncommingDamage-self.DamageData.DamageAmount
    	end	
    	if self.Trash then
            self.Trash:Destroy()
        end
    end,
}

TypeClass = EMESamHVM01
