-----------------------------------------------------------------------------
--  File     : /units/XRL0302/XRL0302_Script.lia
--
--  Author(s): EbolaSoup, Resin Smoker, Optimus Prime, Vissroid, Domino
--
--  Summary  : Cybran Mobile Bomb Script
--
--  Copyright © 2011 4DC_V0.8  All rights reserved.
-----------------------------------------------------------------------------
local CWalkingLandUnit = import('/lua/cybranunits.lua').CWalkingLandUnit
local util = import('/lua/utilities.lua')
local EffectTemplate = import('/lua/EffectTemplates.lua')
local Custom_4D_EffectTemplate = import('/mods/4DC_V0.8/lua/4D_EffectTemplates.lua')
local KamikazeWeapon = import('/lua/sim/DefaultWeapons.lua').KamikazeWeapon

XRL0302 = Class(CWalkingLandUnit) {
    Weapons = {       
        Mobile_Bomb = Class(KamikazeWeapon) {       
            OnFire = function(self) 
                if not self.unit.AlreadyDetonated then
                    -- Disable death weapon after initial firing
                    self.unit.AlreadyDetonated = true
                    self.unit:MineDetonation()                    
                    KamikazeWeapon.OnFire(self)
                end
            end,
        },        
    },
    
    OnStopBeingBuilt = function(self,builder,layer)
        CWalkingLandUnit.OnStopBeingBuilt(self,builder,layer)
        -- Preset unit cloaking
        self:DisableUnitIntel('Cloak')    
        
        -- Global Booleans
        self.StealthEnabled = false
        self.AlreadyDetonated = false
        
        -- Setup stealth and economy starting conditions
        self.BP = self:GetBlueprint()        
        self:SetMaintenanceConsumptionInactive()
        if self.BP.Intel.StealthStartsOn == true then
            self.ToggleStatus = true
        else
            self.ToggleStatus = false
        end  
        self:ForkThread(self.EconomyHeartBeat)                  
        self:RequestRefreshUI()
    end,      
    
    EconomyHeartBeat = function(self)       
        local eCost = self.BP.Economy.MaintenanceConsumptionPerSecondEnergy           
        while not self:IsDead() do                                         
            if not self:IsDead() then                                    
                -- Stealth control logic
                if self:GetAIBrain():GetEconomyStored('Energy') < eCost or self.ToggleStatus == false then
                    if self.StealthEnabled == true then        
                        self:ForkThread(self.StealthDisable)
                    end
                elseif self:GetAIBrain():GetEconomyStored('Energy') > eCost or self.ToggleStatus == true then  
                    if self.StealthEnabled == false then            
                        self:ForkThread(self.StealthEnable)                         
                    end
                end                                                                                                                                                 
            end 
            -- Short delay between checks
            WaitSeconds(1)                                     
        end
    end,    
    
    OnScriptBitSet = function(self, bit)
        -- UI Toggle that turns stealth mesh off
        if not self:IsDead() and bit == 6 then
           self.ToggleStatus = false 
           CWalkingLandUnit.OnScriptBitSet(self, bit)                             
        end
    end,     
     
    OnScriptBitClear = function(self, bit)
        -- UI Toggle that turns stealth mesh on    
        if not self:IsDead() and bit == 6 then
            self.ToggleStatus = true
            CWalkingLandUnit.OnScriptBitClear(self, bit)            
        end
    end,
    
    StealthEnable = function(self)
        if not self:IsDead() and self.StealthEnabled == false then 
            self.StealthEnabled = true 
            self:EnableUnitIntel('Cloak') 
            self:SetMesh('/mods/4DC_V0.8/hook/units/xrl0302/xrl0302_stealth_mesh', true)
            self:SetMaintenanceConsumptionActive()            
        end
    end,    
    
    StealthDisable = function(self)
        if not self:IsDead() and self.StealthEnabled == true then          
            self.StealthEnabled = false     
            self:DisableUnitIntel('Cloak') 
            self:SetMesh(self.BP.Display.MeshBlueprint, true)
            self:SetMaintenanceConsumptionInactive()                       
        end
    end,
    
    OnExtraToggleClear = function(self, ToggleName)
        -- Detonate toggle button
        if ToggleName == 'RULEETC_NukeToggle' then 
            if not self.AlreadyDetonated and not self:BeenDestroyed() then
                self:GetWeaponByLabel('Mobile_Bomb'):FireWeapon()
            end        
        end
    end,

    OnExtraToggleSet = function(self, ToggleName)
        -- Detonate toggle button
        if ToggleName == 'RULEETC_NukeToggle' then      
            if not self.AlreadyDetonated and not self:BeenDestroyed() then
                self:GetWeaponByLabel('Mobile_Bomb'):FireWeapon()
            end        
        end
    end, 
    
    MineDetonation = function(self)
        -- Detonation FX
        self:PlayUnitSound('Detonate')
        local pos = self:GetPosition()
        local army = self:GetArmy()  
        self:ForkThread(self.CreateOuterRingWaveSmokeRing)                      
        for k, v in EffectTemplate.TAntiMatterShellHit01 do                   
            CreateEmitterAtEntity( self, army, v ):ScaleEmitter(0.75):OffsetEmitter(0,0.1,0)                 
        end          
        for k, v in Custom_4D_EffectTemplate.Mine01 do                   
            CreateEmitterAtEntity( self, army, v ):ScaleEmitter(1):OffsetEmitter(0,0.1,0)                 
        end                            
        CreateDecal(pos, util.GetRandomFloat(0,2*math.pi), 'Crater01_albedo', '', 'Albedo', 6, 6, 300, 0, army)
        CreateDecal(pos, util.GetRandomFloat(0,2*math.pi), 'Crater01_normals', '', 'Normals', 6, 6, 300, 0, army)       
        CreateDecal(pos, util.GetRandomFloat(0,2*math.pi), 'nuke_scorch_003_albedo', '', 'Albedo', 10, 10, 300, 0, army)          
        self:ShakeCamera(6, 2.0, 0.5, 1)        
        DamageArea(self, pos, 10, 1, 'Fire', false)
    end, 
    
    CreateOuterRingWaveSmokeRing = function(self)
        local sides = 8
        local angle = (2*math.pi) / sides
        local velocity = 1
        local OffsetMod = 4
        local projectiles = {}

        for i = 0, (sides-1) do
            local X = math.sin(i*angle)
            local Z = math.cos(i*angle)
            local proj =  self:CreateProjectile('/effects/entities/SCUDeathShockwave01/SCUDeathShockwave01_proj.bp', X * OffsetMod , 2, Z * OffsetMod, X, 0, Z)
                :SetVelocity(velocity)
            table.insert( projectiles, proj )
        end  
        
        WaitSeconds( 3 )

        -- Slow projectiles down to normal speed
        for k, v in projectiles do
            v:SetAcceleration(-0.25)
        end         
    end,     
    
    OnKilled = function(self, instigator, type, overkillRatio)
        if not self.AlreadyDetonated and not self:BeenDestroyed() then
            self:GetWeaponByLabel('Mobile_Bomb'):FireWeapon()
        end
        CWalkingLandUnit.OnKilled(self, instigator, type, overkillRatio)
    end,   
          
    DeathThread = function(self)
        -- Override the normal death event to prevent a corpse from being created
        self:Destroy()
    end,             
}
TypeClass = XRL0302