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)

	bool bExplode = (akProjectile && _00E_ExplosiveBarrel_ValidProjectiles.HasForm(akProjectile)) || (akSource && _00E_ExplosiveBarrel_ValidSources.HasForm(akSource))
	
	if ! bExplode
		Actor aggressor = akAggressor as Actor
		if aggressor
			if _00E_A1_FireArrowAmm == None
				_00E_A1_FireArrowAmm = Game.GetForm(0x670EC) as Ammo
			endif
			if _00E_A1_FireArrowME == None
				_00E_A1_FireArrowME = Game.GetForm(0x5BD36) as MagicEffect
			endif
			if aggressor.IsEquipped(_00E_A1_FireArrowAmm) || ( aggressor.HasMagicEffect(_00E_A1_FireArrowME) && aggressor.GetItemCount(_00E_A1_FireArrowAmm) == 0 )
				bExplode = true
			endif
		endif
	endif
	
	If bExplode
		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

MagicEffect Property _00E_A1_FireArrowME Auto
Ammo Property _00E_A1_FireArrowAmm Auto