Scriptname wizMiscMarkerScript extends ObjectReference  

Actor Property PlayerREF Auto
Activator Property wizHagravenHangingBall01Static Auto
Static Property HagravenHangingBall01 Auto
Activator Property wizHagravenHangingBall02Static Auto
Static Property HagravenHangingBall02 Auto
Container Property wizHayBale01Static Auto
Static Property HayBale01 Auto
Furniture Property CraftingSmelterMarker1 Auto
Activator Property wizShovel01 Auto
Static Property MeadBarrel01 Auto
Activator Property wizMeadBarrel01Static Auto
Activator Property wizBlackBriarMeadBarrel Auto
Activator Property wizBlackBriarMeadPrivateReserveBarrel Auto
Activator Property wizHonningbrewMeadBarrel Auto
Activator Property wizSkoomaBarrel Auto
Activator Property wizWaterBarrel Auto
Activator Property wizMeadBarrelBloodDrip01 Auto
Activator Property wizMeadBarrelBloodDrip02 Auto
Activator Property wizCombatDummy01Activator Auto
Activator Property wizCombatDummy02Activator Auto
Activator Property wizCombatDummy03Activator Auto
Activator Property wizArcheryTargetActivator Auto

FormList Property wizParentIssues Auto
FormList Property wizMiscConversionList Auto
FormList Property wizMeadBarrel01List Auto
FormList Property wizMeadBarrelBloodList Auto
FormList Property wizCombatDummy01 Auto
FormList Property wizCombatDummy02 Auto
FormList Property wizCombatDummy03 Auto
FormList Property wizCombatDummyList Auto
FormList Property wizArcheryTargetList Auto

GlobalVariable Property wizDynamicThingsEnabled Auto 
GlobalVariable Property wizOptionMiscsEnabled Auto 
GlobalVariable Property wizOptionDTResetTime Auto 
Actor Property ArngeirREF Auto
wizDTCompatibility Property Compatibility Auto
MiscObject  Property wizStraw Auto

ObjectReference ClosestMisc
ObjectReference MiscContainer
Bool ParentIssues
Float Respawn

Event OnInit()
	;debug.messagebox("Misc Item activator OnInit")
	if MiscContainer == None ;Only fire once
		PlaceMisc()
		Respawn = utility.getCurrentGameTime()
	endIf

endEvent


Event OnCellDetach()
	;Re-enable static misc - this is mainly for unistallation puposes
	if ParentIssues != TRUE ;&& ClosestMisc.isDisabled() != TRUE
		ClosestMisc.enable()
	endIf

	if MiscContainer
		;Disable wood pile container
		MiscContainer.disable()
	else
		self.disable()
		self.delete()
	endIf

	Respawn = utility.getCurrentGameTime()

endEvent

Event OnCellAttach()
	;debug.notification(Compatibility.isSKSELoaded)
	if wizDynamicThingsEnabled.getvalueint() == 1 && wizOptionMiscsEnabled.getvalueint() == 1
		;Find the curent closest barrel  - may be dufferent if Placeable Statics has been removed!
		ClosestMisc= Game.FindClosestReferenceOfAnyTypeInListFromRef(wizMiscConversionList, self, 15)

;		debug.messagebox(closestmisc + " " + closestMisc.isdeleted() + " " + ClosestMisc.isDisabled() + " Scale =" + closestmisc.getscale())

		if ClosestMisc == None || ClosestMisc.isDeleted() || ClosestMisc.isDisabled()
			;Barrel moved by a mod that moved a vanilla object
			MiscContainer.disable()
			MiscContainer.delete()
			self.disable()
			self.Delete()
		else

			;Might this container be respawning?
			if utility.getCurrentGameTime() >= (Respawn + (wizOptionDTResetTime.getvalue() as float))
				;We are going to loop for 3 seconds to see if MiscContainer gets deleted!
				int iLoop = 6
				While iLoop
					;Is the container deleted?
					if MiscContainer.isDeleted()
;						debug.messagebox("MiscContainer Deleted!")
						PlaceMisc()
						iLoop = 0
					else
						Utility.wait(0.5)
						iLoop = (iLoop - 1)
					endIf
				endWhile
				
			endIf


			If ClosestMisc.GetBaseObject() AS Furniture != CraftingSmelterMarker1
				if ParentIssues != TRUE && !wizParentIssues.HasForm(ClosestMisc)
					ClosestMisc.disable()

					if !ClosestMisc.IsDisabled()
						;This catches parent problems and add it to an ignore list to prevent
						debug.trace ("********** wizDYNAMIC THINGS - The Enable State Parent error above has been accounted for and will not occur again for this object **********")
						ParentIssues = TRUE
						;Add to parent issues for logging!
						if !(wizParentIssues.HasForm(ClosestMisc)) 
							wizParentIssues.AddForm(ClosestMisc)
						endIf
;						debug.messagebox(ClosestMisc)
					endIf

				endIf
			endIf

			if miscContainer
				;debug.notification("OnCellAttach enabled")
				MiscContainer.enable()
				
				if wizMeadBarrel01List.HasForm(ClosestMisc.getBaseObject()) || wizMeadBarrelBloodList.HasForm(ClosestMisc.getBaseObject())

					;Setup colors!
					bool FriendlyFaction = False
					cell kCell= self.GetParentCell()
					faction CellFaction = kCell.getFactionOwner()
					if CellFaction && playerref.GetFactionRank(CellFaction) >= 0
						FriendlyFaction= True
					endIf

					int  Highlight = 0
					;Are we in an Inn or Store or FriendlyFaction?
					if  self.getcurrentlocation() && (self.getcurrentlocation().haskeyword(Keyword.getkeyword("LocTypeInn")) || self.getcurrentlocation().haskeyword(Keyword.getkeyword("LocTypeStore")))
						Highlight= 3 ;Gold for money
					elseIF self.getcurrentlocation() && FriendlyFaction == True
						Highlight= 2 ;Green for freebie
					elseIf self.getcurrentlocation() && self.getcurrentlocation().haskeyword(Keyword.getkeyword("LocTypeDwelling"))
						Highlight = 1 ;Red for dwellings
					else
						Highlight = 0 ;Otherwise no highlighting
					endif

					if Highlight == 1 ;Red
						MiscContainer.getbaseobject().setName(Colored_Font("#FF0000", MiscContainer))
					Elseif Highlight == 2 ;Green
						MiscContainer.getbaseobject().setName(Colored_Font("#008000", MiscContainer))
					Elseif Highlight == 3 ;Gold
						MiscContainer.getbaseobject().setName(Colored_Font("#D4A017", MiscContainer))
					Else
						MiscContainer.getbaseobject().setName(Colored_Font("NONE", MiscContainer))
					endIf

;					debug.messagebox(MiscContainer.getbaseobject().GetName())
			
				endIf


				if  self.getcurrentlocation() && self.getcurrentlocation().haskeyword(Keyword.getkeyword("LocTypeHabitation"))
					MiscContainer.SetActorOwner(ArngeirREF.GetActorBase())
				endIf
			else
				self.disable()
				self.delete()
			endIf
		endIf
	EndIf
EndEvent

string function Colored_Font(string Color, ObjectReference Obj)
	string CurrentName = obj.getBaseObject().GetName()
	;See if HTML is already attached
	int StartName = stringUtil.Find(CurrentName, ">", 0)
	int EndName
	if StartName == -1
		;Currentname is our base
	else
		CurrentName = stringUtil.SubString(CurrentName, StartName + 1)
		EndName = stringUtil.Find(CurrentName, "<")
		CurrentName = stringUtil.SubString(CurrentName, 0, (EndName))
	endIf

;	debug.messagebox(CurrentName)	

	if Color == "NONE"
		Return CurrentName
	else
		Return "<font color='" + Color + "'>" + CurrentName + "</font>"
	EndIf

endFunction

Function PlaceMisc()
		;Which misc are we replacing?
		ClosestMisc = Game.FindClosestReferenceOfAnyTypeInListFromRef(wizMiscConversionList, self, 15)
		
		if !ClosestMisc
			;How do we exist then?
			self.disable()
			self.delete()
			return
		endIf

		If ClosestMisc.GetBaseObject() AS Static == HagravenHangingBall01
			MiscContainer = self.placeatme(wizHagravenHangingBall01Static)
		ElseIf ClosestMisc.GetBaseObject() AS Static == HagravenHangingBall02
			MiscContainer = self.placeatme(wizHagravenHangingBall02Static)
		ElseIf ClosestMisc.GetBaseObject() AS Static == HayBale01
			MiscContainer = self.placeatme(wizHayBale01Static)
			;What are we adding?
			if Compatibility.isHFLoaded
				;Add HF Straw
				MiscContainer.additem(Game.GetFormFromFile(0x01005A68, "HearthFires.esm") as MiscObject,3)
			else
				;MiscContainer.additem(wizStraw, 1)
			endIf
		ElseIf ClosestMisc.GetBaseObject() AS Furniture == CraftingSmelterMarker1
			MiscContainer = self.placeatme(wizShovel01)
			MiscContainer.MoveTo(self,150.0 * Math.Sin(MiscContainer.GetAngleZ() + 90), 150.0 * Math.Cos(MiscContainer.GetAngleZ() + 90),50)
			;debug.notification(self.getanglez())
			MiscContainer.SetAngle(self.GetAngleX(), 15, self.GetAngleZ())
			;MiscContainer.SetMotionType(MiscContainer.Motion_Keyframed, true)
		ElseIf wizMeadBarrel01List.HasForm(ClosestMisc.getBaseObject())
			;Is it considered stealing here?

			;Does the player belong to the faction that owns this cell?
			bool FriendlyFaction = False
			int  Highlight = 0
			cell kCell= self.GetParentCell()
			faction CellFaction = kCell.getFactionOwner()
			if CellFaction && playerref.GetFactionRank(CellFaction) >= 0
				FriendlyFaction= True
			endIf

			;Are we in an Inn or Store or FriendlyFaction?
			if  self.getcurrentlocation() && (self.getcurrentlocation().haskeyword(Keyword.getkeyword("LocTypeInn")) || self.getcurrentlocation().haskeyword(Keyword.getkeyword("LocTypeStore")))
				Highlight= 3 ;Gold for money
			elseIf self.getcurrentlocation() && FriendlyFaction == True
				Highlight= 2 ;Green for freebie
			elseIf self.getcurrentlocation() && self.getcurrentlocation().haskeyword(Keyword.getkeyword("LocTypeDwelling"))
				Highlight = 1 ;Red for dwellings
			else
				Highlight = 0 ;Otherwise no highlighting
			endif
	
			int Chance = utility.randomint(1,100)
			if Chance <=77 ;77% for Nord Mead or Skooma or Water depending on variables
				if Compatibility.isRND
					if self.getCurrentLocation() && self.getcurrentlocation().haskeyword(Keyword.getkeyword("LocTypeBanditCamp"))
						;RND and Bandit Camp
						if Chance <=27 ;27%
							MiscContainer = self.placeatme(wizMeadBarrel01Static)
						elseIf Chance <= 52 ;25%
							MiscContainer = self.placeatme(wizWaterBarrel)
						else ;25%
							MiscContainer = self.placeatme(wizSkoomaBarrel)
						EndIf
					else
						;RND Only
						if Chance <=52 ;52%
							MiscContainer = self.placeatme(wizMeadBarrel01Static)
						else ;25%
							MiscContainer = self.placeatme(wizWaterBarrel)
						EndIf
					endIf
				else
					if self.getCurrentLocation() && self.getcurrentlocation().haskeyword(Keyword.getkeyword("LocTypeBanditCamp"))
						;Vanilla and bandit camp
						if Chance <=52 ;52%
							MiscContainer = self.placeatme(wizMeadBarrel01Static)
						else ;25%
							MiscContainer = self.placeatme(wizSkoomaBarrel)
						EndIf
					else
						;Vanilla
						MiscContainer = self.placeatme(wizMeadBarrel01Static)
					endIf
				endIf
			elseif Chance <=89 ;12%
				MiscContainer = self.placeatme(wizBlackBriarMeadBarrel)
			elseif Chance <=99 ;10%
				MiscContainer = self.placeatme(wizHonningbrewMeadBarrel)
			elseif Chance <=100 ;1%
				MiscContainer = self.placeatme(wizBlackBriarMeadPrivateReserveBarrel)
			endIf

			if Highlight == 1 ;Red
				MiscContainer.getbaseobject().setName(Colored_Font("#FF0000", MiscContainer))
			Elseif Highlight == 2 ;Green
				MiscContainer.getbaseobject().setName(Colored_Font("#008000", MiscContainer))
			Elseif Highlight == 3 ;Gold
				MiscContainer.getbaseobject().setName(Colored_Font("#D4A017", MiscContainer))
			Else
				MiscContainer.getbaseobject().setName(Colored_Font("NONE", MiscContainer))
			endIf

;			debug.messagebox(MiscContainer.getbaseobject().GetName())

		ElseIf wizMeadBarrelBloodList.HasForm(ClosestMisc.getBaseObject())
			;Is it considered stealing here?

			;Does the player belong to the faction that owns this cell?
			bool FriendlyFaction = False

			int  Highlight = 0
			;Are we in an Inn or Store or FriendlyFaction?
			if  self.getcurrentlocation() && (self.getcurrentlocation().haskeyword(Keyword.getkeyword("LocTypeInn")) || self.getcurrentlocation().haskeyword(Keyword.getkeyword("LocTypeStore")))
				Highlight= 3 ;Gold for money
			elseIF self.getcurrentlocation() && FriendlyFaction == True
				Highlight= 2 ;Green for freebie
			elseIf self.getcurrentlocation() && self.getcurrentlocation().haskeyword(Keyword.getkeyword("LocTypeDwelling"))
				Highlight = 1 ;Red for dwellings
			else
				Highlight = 0 ;Otherwise no highlighting
			endif
	
			cell kCell= self.GetParentCell()
			faction CellFaction = kCell.getFactionOwner()
			if CellFaction && playerref.GetFactionRank(CellFaction) >= 0
				FriendlyFaction= True
			endIf

			If ClosestMisc.GetBaseObject() AS Form == Game.GetFormFromFile(0x0100482D, "Dawnguard.esm") as Form ;MeadBarrel_BloodDrip01
				MiscContainer = self.placeatme(wizMeadBarrelBloodDrip01)
			ElseIf ClosestMisc.GetBaseObject() AS Form == Game.GetFormFromFile(0x01004847, "Dawnguard.esm") as Form ;MeadBarrel_BloodDrip02
				MiscContainer = self.placeatme(wizMeadBarrelBloodDrip02)
			EndIf

			if Highlight == 1 ;Red
				MiscContainer.getbaseobject().setName(Colored_Font("#FF0000", MiscContainer))
			Elseif Highlight == 2 ;Green
				MiscContainer.getbaseobject().setName(Colored_Font("#008000", MiscContainer))
			Elseif Highlight == 3 ;Gold
				MiscContainer.getbaseobject().setName(Colored_Font("#D4A017", MiscContainer))
			Else
				MiscContainer.getbaseobject().setName(Colored_Font("NONE", MiscContainer))
			endIf

		ElseIf wizCombatDummyList.HasForm(ClosestMisc.getBaseObject())
			If wizCombatDummy01.HasForm(ClosestMisc.getBaseObject())
				MiscContainer = self.placeatme(wizCombatDummy01Activator)
			elseIf wizCombatDummy02.HasForm(ClosestMisc.getBaseObject())
				MiscContainer = self.placeatme(wizCombatDummy02Activator)
			elseIf wizCombatDummy03.HasForm(ClosestMisc.getBaseObject())
				MiscContainer = self.placeatme(wizCombatDummy03Activator)
			endIf
		ElseIf wizArcheryTargetList.HasForm(ClosestMisc.getBaseObject())
			MiscContainer = self.placeatme(wizArcheryTargetActivator)
		EndIf

		If ClosestMisc.GetBaseObject() AS Furniture != CraftingSmelterMarker1
			MiscContainer.SetAngle(self.GetAngleX(), self.GetAngleY(), self.GetAngleZ())
		endIf
		MiscContainer.SetScale(ClosestMisc.getscale())

		;Make misc object owned???
		if  self.getcurrentlocation().haskeyword(Keyword.getkeyword("LocTypeHabitation"))
			MiscContainer.SetActorOwner(ArngeirREF.GetActorBase())
		endIf

		utility.wait(1) ;This should help reduce flicker

		If ClosestMisc.GetBaseObject() AS Furniture != CraftingSmelterMarker1
			if ParentIssues != TRUE && !wizParentIssues.HasForm(ClosestMisc)
				ClosestMisc.disable()
				if !ClosestMisc.IsDisabled()
					;This catches parent problems and add it to an ignore list to prevent
					debug.trace ("********** wizDYNAMIC THINGS - The Enable State Parent error above has been accounted for and will not occur again for this object **********")
					ParentIssues = TRUE
					;Add to parent issues for logging!
					if !(wizParentIssues.HasForm(ClosestMisc)) 
						wizParentIssues.AddForm(ClosestMisc)
					endIf
;					debug.messagebox(ClosestMisc)
				endIf
			else
				;Known parent issues!
				ParentIssues = TRUE
			endIf
		EndIf
endFunction