Scriptname _00E_ExplosiveBarrelsScript extends ObjectReference  

Import Math
Import Utility

; This script is used to control the behaviour of gunpowder-barrels.

;=====================================================================================
;              							EVENTS                    					 
;=====================================================================================

Event OnHit(ObjectReference akAggressor, Form akSource, Projectile akProjectile, bool abPowerAttack, bool abSneakAttack, bool abBashAttack, bool abHitBlocked)

	If (akProjectile && _00E_ExplosiveBarrel_ValidProjectiles.HasForm(akProjectile)) || (akSource && _00E_ExplosiveBarrel_ValidSources.HasForm(akSource))
		If bExploded == False
			bExploded = True
			If ExplosionMarkerRef == None
				ExplosionMarkerRef = Self.PlaceAtMe(XMarker)
			EndIf
			Self.DamageObject(100) ; Damage the object to trigger the OnDestructionStageChanged events
			RegisterForSingleUpdate(30.0)
		EndIf
	EndIf

EndEvent

Event OnDestructionStageChanged(Int aiOldStage, Int aiCurrentStage)

	if aiCurrentStage == 1
		UnregisterForUpdate()

		Game.ShakeCamera(afStrength = 0.4)
		; Place VFX and explosion
		If ExplosionMarkerRef
			ExplosionMarkerRef.PlaceAtMe(_00E_ExplosiveBarrelEXP_Damage)
		Else
			Self.PlaceAtMe(_00E_ExplosiveBarrelEXP_Damage)
		EndIf
		Wait(0.1)
		If ExplosionMarkerRef
			ExplosionMarkerRef.PlaceAtMe(_00E_ExplosiveBarrelEXP_VFX)
		Else
			Self.PlaceAtMe(_00E_ExplosiveBarrelEXP_VFX)
		EndIf

		DeleteExplosionMarker()
	EndIf

EndEvent

Event OnUpdate()
	; Failsafe cleanup
	DeleteExplosionMarker()
EndEvent

Function DeleteExplosionMarker()
	If ExplosionMarkerRef
		ExplosionMarkerRef.Disable()
		ExplosionMarkerRef.Delete()
		ExplosionMarkerRef = None
	EndIf
EndFunction

;=====================================================================================
;              							PROPERTIES                    					 
;=====================================================================================


Explosion Property _00E_ExplosiveBarrelEXP_VFX Auto
Explosion Property _00E_ExplosiveBarrelEXP_Damage Auto

Formlist Property _00E_ExplosiveBarrel_ValidSources Auto
Formlist Property _00E_ExplosiveBarrel_ValidProjectiles Auto
Static Property XMarker Auto

Bool bExploded = False
ObjectReference ExplosionMarkerRef