Decompiled source of ActionBar Redux v1.0.2

ModifAmorphic.Outward.ActionUI.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using ModifAmorphic.Outward.Unity.ActionMenus;
using ModifAmorphic.Outward.Unity.ActionUI;
using ModifAmorphic.Outward.Unity.ActionUI.Controllers;
using ModifAmorphic.Outward.Unity.ActionUI.Data;
using ModifAmorphic.Outward.Unity.ActionUI.EquipmentSets;
using ModifAmorphic.Outward.Unity.ActionUI.Extensions;
using ModifAmorphic.Outward.Unity.ActionUI.Models.EquipmentSets;
using ModifAmorphic.Outward.Unity.ActionUI.Services;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("ModifAmorphic.Outward.ActionUI")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a580093fb59052c6205677075b91d046d390cb6a")]
[assembly: AssemblyProduct("ModifAmorphic.Outward.ActionUI")]
[assembly: AssemblyTitle("ModifAmorphic.Outward.ActionUI")]
[assembly: AssemblyVersion("1.0.0.0")]
public class ActionImages : MonoBehaviour
{
	public static readonly Color DisabledColor = new Color(0f, 0f, 0f, 0.9f);

	public Image BaseImage;

	private Dictionary<string, Image> _bottomImages = new Dictionary<string, Image>();

	private Dictionary<string, Image> _topImages = new Dictionary<string, Image>();

	private const string DisabledKey = "disabled";

	public Image AddOrUpdateImage(ActionSlotIcon slotIcon)
	{
		if (_bottomImages.TryGetValue(slotIcon.Name, out var value))
		{
			if ((Object)(object)value.sprite != (Object)(object)slotIcon.Icon)
			{
				value.sprite = slotIcon.Icon;
			}
			return value;
		}
		Image val = Object.Instantiate<Image>(BaseImage, ((Component)this).transform);
		val.sprite = slotIcon.Icon;
		val.overrideSprite = null;
		((Component)val).gameObject.SetActive(true);
		((Object)val).name = slotIcon.Name;
		if (!slotIcon.IsTopSprite)
		{
			_bottomImages.Add(slotIcon.Name, val);
		}
		else
		{
			_topImages.Add(slotIcon.Name, val);
		}
		SetSiblingIndexes();
		return val;
	}

	public void ToggleEnabled(bool enabled)
	{
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		if (enabled && _bottomImages.TryGetValue("disabled", out var value))
		{
			Object.Destroy((Object)(object)((Component)value).gameObject);
			_bottomImages.Remove("disabled");
		}
		else if (!enabled && !_bottomImages.ContainsKey("disabled"))
		{
			value = AddOrUpdateImage(new ActionSlotIcon
			{
				Name = "disabled",
				Icon = null
			});
			((Graphic)value).color = DisabledColor;
		}
	}

	public void ClearImages()
	{
		foreach (Image value in _bottomImages.Values)
		{
			if ((Object)(object)((value != null) ? ((Component)value).gameObject : null) != (Object)null)
			{
				((Component)value).gameObject.Destroy();
			}
		}
		foreach (Image value2 in _topImages.Values)
		{
			if ((Object)(object)((value2 != null) ? ((Component)value2).gameObject : null) != (Object)null)
			{
				((Component)value2).gameObject.Destroy();
			}
		}
		_bottomImages.Clear();
		_topImages.Clear();
	}

	private void SetSiblingIndexes()
	{
		int num = 0;
		foreach (Image value in _bottomImages.Values)
		{
			((Component)value).transform.SetSiblingIndex(num);
			num++;
		}
		foreach (Image value2 in _topImages.Values)
		{
			((Component)value2).transform.SetSiblingIndex(num);
			num++;
		}
	}
}
public class ToggleChild : MonoBehaviour
{
	public Color EnabledColor = new Color(0.8392157f, 0.7215686f, 0.3921569f, 1f);

	public Color DisabledColor = new Color(Color.gray.r, Color.gray.g, Color.gray.b, 0.7f);

	public InputField InputField;

	public Selectable ChildToggle;

	public Selectable[] ChildToggles;

	public void Toggle(bool enabled)
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		((Graphic)InputField.textComponent).color = (enabled ? EnabledColor : DisabledColor);
		if (ChildToggles != null)
		{
			for (int i = 0; i < ChildToggles.Length; i++)
			{
				ChildToggles[i].interactable = enabled;
			}
		}
	}
}
public class ToggleParent : MonoBehaviour
{
	public List<ToggleChild> Children;

	private void Awake()
	{
		((UnityEvent<bool>)(object)((Component)this).GetComponent<Toggle>().onValueChanged).AddListener((UnityAction<bool>)ToggleChildren);
	}

	private void Start()
	{
		ToggleChildren(((Component)this).GetComponent<Toggle>().isOn);
	}

	public void ToggleChildren(bool enabled)
	{
		if (Children == null)
		{
			return;
		}
		foreach (ToggleChild child in Children)
		{
			child.Toggle(enabled);
		}
	}
}
namespace ModifAmorphic.Outward.Unity.ActionMenus
{
	[UnityScriptComponent]
	public class ActionItemView : MonoBehaviour, IEventSystemHandler, IPointerEnterHandler, IPointerExitHandler
	{
		public ActionImages ActionImages;

		public MouseClickListener MouseClickListener;

		public UnityEvent<int> OnSlotActionSet;

		public UnityEvent<int> OnSlotActionReset;

		private ISlotAction _slotAction;

		private int _viewID = -1;

		private Button _button;

		private Text _text;

		private Text _stackText;

		private Image _borderImage;

		private Image _borderHighlightImage;

		private bool _isAwake;

		public ISlotAction SlotAction => _slotAction;

		public int ViewID => _viewID;

		public Button Button => _button;

		public Image BorderImage => _borderImage;

		public Image ActionBorderHighlight => _borderHighlightImage;

		private void Awake()
		{
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Expected O, but got Unknown
			_button = ((Component)this).GetComponentInChildren<Button>(true);
			_text = ((Component)this).GetComponentsInChildren<Text>(true).First((Text t) => ((Object)t).name.Equals("ActionText"));
			_stackText = ((Component)_button).GetComponentsInChildren<Text>(true).First((Text t) => ((Object)t).name.Equals("StackText"));
			_borderImage = ((Component)this).GetComponentsInChildren<Image>(true).First((Image i) => ((Object)i).name == "ActionBorder");
			_borderHighlightImage = ((Component)this).GetComponentsInChildren<Image>(true).First((Image i) => ((Object)i).name == "ActionBorderHighlight");
			((Behaviour)_borderHighlightImage).enabled = false;
			((Behaviour)_borderImage).enabled = true;
			MouseClickListener.OnRightClick.AddListener(new UnityAction(ResetViewItem));
			_isAwake = true;
		}

		public void SetViewID(int viewID)
		{
			_viewID = viewID;
		}

		public void SetViewItem(ISlotAction action)
		{
			if (_slotAction != null)
			{
				DebugLogger.Log("SetViewItem: ClearImages()");
				_slotAction.OnIconsChanged -= UpdateActionIcons;
				ActionImages.ClearImages();
			}
			_slotAction = action;
			for (int i = 0; i < _slotAction.ActionIcons.Length; i++)
			{
				DebugLogger.Log($"SetViewItem: AddOrUpdateImage({i})");
				ActionImages.AddOrUpdateImage(_slotAction.ActionIcons[i]);
			}
			DebugLogger.Log("SetViewItem: Setting action text.");
			_text.text = action.DisplayName;
			_stackText.text = ((action.Stack != null && action.Stack.IsStackable && action.Stack.GetAmount() > 0) ? action.Stack.GetAmount().ToString() : string.Empty);
			if (action.HasDynamicIcon)
			{
				action.OnIconsChanged += UpdateActionIcons;
			}
			DebugLogger.Log($"SetViewItem: Raising OnSlotActionSet for ViewID {ViewID}.");
			OnSlotActionSet.Invoke(ViewID);
		}

		public void ResetViewItem()
		{
			if (_slotAction != null)
			{
				_slotAction.OnIconsChanged -= UpdateActionIcons;
			}
			ActionImages?.ClearImages();
			_slotAction = null;
			_text.text = string.Empty;
			_stackText.text = string.Empty;
			DebugLogger.Log($"SetViewItem: Raising OnSlotActionReset for ViewID {ViewID}.");
			OnSlotActionReset.Invoke(ViewID);
		}

		private void UpdateActionIcons(ActionSlotIcon[] icons)
		{
			ActionImages.ClearImages();
			for (int i = 0; i < _slotAction.ActionIcons.Length; i++)
			{
				ActionImages.AddOrUpdateImage(_slotAction.ActionIcons[i]);
			}
		}

		public void OnPointerEnter(PointerEventData eventData)
		{
			if (_isAwake)
			{
				((Behaviour)_borderHighlightImage).enabled = true;
				((Behaviour)_borderImage).enabled = false;
			}
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			if (_isAwake)
			{
				((Behaviour)_borderHighlightImage).enabled = false;
				((Behaviour)_borderImage).enabled = true;
			}
		}
	}
	[UnityScriptComponent]
	public class ActionMenuResources : MonoBehaviour
	{
		public Dictionary<string, Sprite> SpriteResources;

		public static ActionMenuResources Instance { get; private set; }

		private void Awake()
		{
			SpriteResources = new Dictionary<string, Sprite>();
			GameObject gameObject = ((Component)((Component)this).transform.Find("SpriteImages")).gameObject;
			Image[] componentsInChildren = gameObject.GetComponentsInChildren<Image>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				SpriteResources.Add(((Object)componentsInChildren[i]).name, componentsInChildren[i].sprite);
				((Component)componentsInChildren[i]).gameObject.SetActive(false);
			}
			Instance = this;
		}
	}
	[UnityScriptComponent]
	public class ActionSlot : MonoBehaviour
	{
		private MouseClickListener _mouseClickListener;

		private ISlotAction _slotAction;

		private IActionSlotConfig _config;

		private Transform _slotPanel;

		private Canvas _parentCanvas;

		private CanvasGroup _canvasGroup;

		private Image _hotkeyPanel;

		private Text _keyText;

		private Button _keyButton;

		private Button _actionButton;

		private ActionImages _actionImages;

		private Image _cooldownImage;

		private Image _cooldownTextBackground;

		private Text _cooldownText;

		private Text _stackText;

		private Image _emptyImage;

		private Image _borderImage;

		private Dictionary<BarPositions, ProgressBar> _progressBars = new Dictionary<BarPositions, ProgressBar>();

		private IActionSlotController _controller;

		public HotbarsContainer HotbarsContainer { get; internal set; }

		public MouseClickListener MouseClickListener => _mouseClickListener;

		public int HotbarIndex { get; internal set; }

		public int SlotIndex { get; internal set; }

		public int SlotId => HotbarIndex * 10000 + SlotIndex;

		public ISlotAction SlotAction
		{
			get
			{
				return _slotAction;
			}
			internal set
			{
				_slotAction = value;
			}
		}

		public IActionSlotConfig Config
		{
			get
			{
				return _config;
			}
			internal set
			{
				_config = value;
			}
		}

		public Transform SlotPanel => _slotPanel;

		public Canvas ParentCanvas => _parentCanvas;

		public CanvasGroup CanvasGroup => _canvasGroup;

		public Image HotkeyPanel => _hotkeyPanel;

		public Text KeyText => _keyText;

		public Button KeyButton => _keyButton;

		public Button ActionButton => _actionButton;

		public ActionImages ActionImages => _actionImages;

		public Image CooldownImage => _cooldownImage;

		public Image CooldownTextBackground => _cooldownTextBackground;

		public Text CooldownText => _cooldownText;

		public Text StackText => _stackText;

		public Image EmptyImage => _emptyImage;

		public Image BorderImage => _borderImage;

		public Dictionary<BarPositions, ProgressBar> ProgressBars => _progressBars;

		public IActionSlotController Controller => _controller;

		public bool IsInEditMode => HotbarsContainer.IsInHotkeyEditMode;

		public Func<Action, bool> ActionRequested { get; private set; }

		private void Awake()
		{
			SetComponents();
			if (((Object)this).name != "BaseActionSlot")
			{
				((Object)this).name = $"ActionSlot_{HotbarIndex}_{SlotIndex}";
				_controller = new ActionSlotController(this);
				_controller.ActionSlotAwake();
			}
		}

		private void OnEnable()
		{
			if (SlotAction != null)
			{
				DebugLogger.Log("ActionSlot::OnEnable: Reassigning SlotAction " + SlotAction.DisplayName);
				_controller.AssignSlotAction(SlotAction, surpressChangeFlag: true);
			}
		}

		private void Update()
		{
			_controller.ActionSlotUpdate();
		}

		private void SetComponents()
		{
			Transform parent = ((Component)this).transform.parent;
			object parentCanvas;
			if (parent == null)
			{
				parentCanvas = null;
			}
			else
			{
				Transform parent2 = parent.parent;
				parentCanvas = ((parent2 != null) ? ((Component)parent2).GetComponent<Canvas>() : null);
			}
			_parentCanvas = (Canvas)parentCanvas;
			_slotPanel = ((Component)this).transform.Find("SlotPanel");
			_canvasGroup = ((Component)this).GetComponent<CanvasGroup>();
			_hotkeyPanel = ((Component)((Component)this).transform.Find("HotkeyPanel")).GetComponent<Image>();
			_keyText = ((Component)_hotkeyPanel).GetComponentsInChildren<Text>(true).First((Text t) => ((Object)t).name == "KeyText");
			_keyButton = ((Component)_hotkeyPanel).GetComponentsInChildren<Button>(true).First((Button t) => ((Object)t).name == "KeyButton");
			_borderImage = ((Component)_slotPanel).GetComponentsInChildren<Image>(true).First((Image i) => ((Object)i).name == "ActionBorder");
			_actionButton = ((Component)_slotPanel).GetComponentInChildren<Button>(true);
			_mouseClickListener = ((Component)_actionButton).GetComponent<MouseClickListener>();
			_actionImages = ((Component)_actionButton).GetComponentInChildren<ActionImages>();
			_progressBars.Add(BarPositions.Top, ((Component)_actionButton).GetComponentsInChildren<ProgressBar>().First((ProgressBar s) => ((Object)s).name == "TopBar"));
			_progressBars.Add(BarPositions.Right, ((Component)_actionButton).GetComponentsInChildren<ProgressBar>().First((ProgressBar s) => ((Object)s).name == "RightBar"));
			_progressBars.Add(BarPositions.Bottom, ((Component)_actionButton).GetComponentsInChildren<ProgressBar>().First((ProgressBar s) => ((Object)s).name == "BottomBar"));
			_progressBars.Add(BarPositions.Left, ((Component)_actionButton).GetComponentsInChildren<ProgressBar>().First((ProgressBar s) => ((Object)s).name == "LeftBar"));
			_stackText = ((Component)_actionButton).GetComponentsInChildren<Text>().First((Text t) => ((Object)t).name == "StackText");
			_cooldownText = ((Component)_actionButton).GetComponentsInChildren<Text>().First((Text t) => ((Object)t).name == "CooldownText");
			_cooldownTextBackground = ((Component)_actionButton).GetComponentsInChildren<Image>().First((Image i) => ((Object)i).name == "CooldownTextBackground");
			_cooldownImage = ((Component)_actionButton).GetComponentsInChildren<Image>().First((Image i) => ((Object)i).name == "CooldownImage");
			_emptyImage = ((Component)_actionButton).GetComponentsInChildren<Image>().First((Image i) => ((Object)i).name == "EmptyImage");
		}

		internal void SetButtonNormalColor(Color color)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			ColorBlock colors = ((Selectable)ActionButton).colors;
			((ColorBlock)(ref colors)).normalColor = color;
			((Selectable)ActionButton).colors = colors;
		}
	}
	[UnityScriptComponent]
	public class ActionsViewer : MonoBehaviour, IActionMenu
	{
		public delegate void SlotActionSelected(int slotId, ISlotAction slotAction);

		public PlayerActionMenus PlayerMenu;

		public ViewerLeftNav LeftNav;

		private GridLayoutGroup _gridLayout;

		public GameObject BaseGridAction;

		private int _slotId;

		public bool IsShowing => ((Component)this).gameObject.activeSelf;

		public bool HasData => GetViewData() != null;

		public UnityEvent OnShow { get; } = new UnityEvent();


		public UnityEvent OnHide { get; } = new UnityEvent();


		public event SlotActionSelected OnSlotActionSelected;

		private void Awake()
		{
			_gridLayout = ((Component)this).GetComponentInChildren<GridLayoutGroup>();
			BaseGridAction.SetActive(false);
			Hide();
		}

		private void Start()
		{
			Clear();
		}

		public void Clear()
		{
			ActionItemView[] componentsInChildren = ((Component)this).GetComponentsInChildren<ActionItemView>();
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				if (((Object)componentsInChildren[i]).name != "BaseSlotPanel")
				{
					((Component)componentsInChildren[i]).gameObject.Destroy();
				}
			}
		}

		public void LoadData(IEnumerable<ISlotAction> actionViews)
		{
			Clear();
			if (!HasData)
			{
				return;
			}
			foreach (ISlotAction actionView in actionViews)
			{
				AddActionView(actionView);
			}
		}

		public void AddActionView(ISlotAction slotAction)
		{
			AddGridItem(slotAction);
		}

		public void Show(int slotId)
		{
			_slotId = slotId;
			if (!((Component)this).gameObject.activeSelf)
			{
				((Component)this).gameObject.SetActive(true);
			}
			InitLeftNav();
			DoNextFrame(LeftNav.ClickSelectedTab);
			UnityEvent onShow = OnShow;
			if (onShow != null)
			{
				onShow.Invoke();
			}
		}

		public void Hide()
		{
			_slotId = 0;
			if (((Component)this).gameObject.activeSelf)
			{
				((Component)this).gameObject.SetActive(false);
			}
			UnityEvent onHide = OnHide;
			if (onHide != null)
			{
				onHide.Invoke();
			}
		}

		private void InitLeftNav()
		{
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			LeftNav.ClearViewTabs();
			IActionViewData viewData = GetViewData();
			if (viewData.GetActionsTabData() != null)
			{
				foreach (IActionsDisplayTab tabView in from d in viewData.GetActionsTabData()
					orderby d.TabOrder
					select d)
				{
					Button val = LeftNav.AddViewTab(tabView.DisplayName);
					((UnityEvent)val.onClick).AddListener((UnityAction)delegate
					{
						LoadData(tabView.GetSlotActions());
					});
				}
			}
			((UnityEvent)LeftNav.AddViewTab("All").onClick).AddListener((UnityAction)delegate
			{
				LoadData(viewData.GetAllActions());
			});
		}

		private IActionViewData GetViewData()
		{
			return Psp.Instance.GetServicesProvider(PlayerMenu.PlayerID).GetService<IActionViewData>();
		}

		private void AddGridItem(ISlotAction slotAction)
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			GameObject val = Object.Instantiate<GameObject>(BaseGridAction, ((Component)_gridLayout).transform);
			int num = ((Component)_gridLayout).GetComponentsInChildren<ActionItemView>().Count();
			val.SetActive(true);
			ActionItemView actionItem = val.GetComponent<ActionItemView>();
			actionItem.SetViewItem(slotAction);
			((Object)actionItem).name = "SlotActionView_" + num;
			((UnityEvent)actionItem.Button.onClick).AddListener((UnityAction)delegate
			{
				RaiseSelectionAndHide(_slotId, actionItem.SlotAction);
			});
		}

		private void RaiseSelectionAndHide(int slotId, ISlotAction slotAction)
		{
			this.OnSlotActionSelected?.Invoke(slotId, slotAction);
			Clear();
			DoNextFrame(Hide);
		}

		private void DoNextFrame(Action action)
		{
			((MonoBehaviour)this).StartCoroutine(NextFrameCoroutine(action));
		}

		private IEnumerator NextFrameCoroutine(Action action)
		{
			yield return null;
			action();
		}
	}
	[UnityScriptComponent]
	public class ArrowInput : MonoBehaviour
	{
		public Button LeftArrow;

		public Button RightArrow;

		public InputField InputText;

		public int Minimum = 1;

		public int Maximum = 100;

		public UnityEvent<int> OnValueChanged;

		public int Amount
		{
			get
			{
				int result;
				return int.TryParse(InputText.text, out result) ? result : Minimum;
			}
		}

		private void Start()
		{
			((UnityEvent<string>)(object)InputText.onValueChanged).AddListener((UnityAction<string>)delegate
			{
				ValidateInput(Amount);
			});
		}

		public void SetAmount(int amount)
		{
			if (amount >= Minimum && amount <= Maximum)
			{
				InputText.text = amount.ToString();
			}
		}

		public void IncreaseAmount()
		{
			if (Amount < Maximum)
			{
				InputText.text = (Amount + 1).ToString();
			}
		}

		public void DecreaseAmount()
		{
			if (Amount > Minimum)
			{
				InputText.text = (Amount - 1).ToString();
			}
		}

		private void ValidateInput(int amount)
		{
			int num = amount;
			if (amount < Minimum)
			{
				num = Minimum;
			}
			else if (amount > Maximum)
			{
				num = Maximum;
			}
			InputText.SetTextWithoutNotify(num.ToString());
			OnValueChanged.Invoke(num);
		}
	}
	[UnityScriptComponent]
	public class ConfirmationPanel : MonoBehaviour
	{
		public Button ConfirmButton;

		public Button CancelButton;

		public Text PromptText;

		public Text DisplayText;

		private bool _isShowInvoked;

		private Action _confirmationAction;

		public bool IsShowing => ((Component)this).gameObject.activeSelf;

		public UnityEvent OnShow { get; } = new UnityEvent();


		public UnityEvent OnHide { get; } = new UnityEvent();


		private void Awake()
		{
			if (!_isShowInvoked)
			{
				Hide(raiseEvent: false);
			}
		}

		public void Show(Action confirmationAction, string promptText)
		{
			PromptText.text = promptText;
			_confirmationAction = confirmationAction;
			_isShowInvoked = true;
			((Component)this).gameObject.SetActive(true);
			OnShow.TryInvoke();
		}

		public void Hide()
		{
			Hide(raiseEvent: true);
		}

		private void Hide(bool raiseEvent)
		{
			((Component)this).gameObject.SetActive(false);
			_isShowInvoked = false;
			if (raiseEvent)
			{
				OnHide.TryInvoke();
			}
		}

		public void OnConfirm()
		{
			_confirmationAction();
			Hide();
		}
	}
	[UnityScriptComponent]
	public class DurabilityDisplay : MonoBehaviour
	{
		public PlayerActionMenus PlayerActionMenus;

		public DurabilitySlot Head;

		public DurabilitySlot Chest;

		public DurabilitySlot RightHand;

		public DurabilitySlot LeftHand;

		public DurabilitySlot Feet;

		private Canvas _canvas;

		private PositionableUI _positionable;

		private Dictionary<EquipSlots, DurabilitySlot> _durabilitySlots = new Dictionary<EquipSlots, DurabilitySlot>();

		private bool isAwake = false;

		private Dictionary<EquipSlots, float> _displayMinimums = new Dictionary<EquipSlots, float>();

		private Dictionary<EquipSlots, Coroutine> _coroutines = new Dictionary<EquipSlots, Coroutine>();

		public Dictionary<EquipSlots, DurabilitySlot> DurabilitySlots => _durabilitySlots;

		public bool IsAwake => isAwake;

		public UnityEvent OnAwake { get; } = new UnityEvent();


		private void Awake()
		{
			_canvas = ((Component)this).GetComponent<Canvas>();
			_positionable = ((Component)this).GetComponent<PositionableUI>();
			if ((Object)(object)_positionable != (Object)null)
			{
				_positionable.OnIsPositionableChanged.AddListener((UnityAction<bool>)delegate
				{
					RefreshDisplay();
				});
			}
			_durabilitySlots.Add(EquipSlots.Head, Head);
			_durabilitySlots.Add(EquipSlots.Chest, Chest);
			_durabilitySlots.Add(EquipSlots.RightHand, RightHand);
			_durabilitySlots.Add(EquipSlots.LeftHand, LeftHand);
			_durabilitySlots.Add(EquipSlots.Feet, Feet);
			foreach (DurabilitySlot value in _durabilitySlots.Values)
			{
				DurabilitySlot changedSlot = value;
				value.OnValueChanged += delegate
				{
					OnSlotValueChanged(changedSlot);
				};
			}
			isAwake = true;
			OnAwake.TryInvoke();
		}

		private void Start()
		{
			UnityServicesProvider servicesProvider = Psp.Instance.GetServicesProvider(PlayerActionMenus.PlayerID);
			if (!servicesProvider.TryGetService<DurabilityDisplay>(out var _))
			{
				servicesProvider.AddSingleton(this);
			}
			RefreshDisplay();
		}

		public void TrackDurability(IDurability durability)
		{
			StopTracking(durability.DurableEquipmentSlot);
			SetMinimumDisplayValue(durability.DurableEquipmentSlot, durability.MinimumDisplayValue);
			foreach (ColorRange colorRange in durability.ColorRanges)
			{
				_durabilitySlots[durability.DurableEquipmentSlot].AddColorRange(colorRange);
			}
			_durabilitySlots[durability.DurableEquipmentSlot].SetEquipmentType(durability.DurableEquipmentType);
			_coroutines.Add(durability.DurableEquipmentSlot, ((MonoBehaviour)this).StartCoroutine(SetDurabilityValue(_durabilitySlots[durability.DurableEquipmentSlot], durability.GetDurabilityRatio)));
			RefreshDisplay();
		}

		public void StopTracking(EquipSlots slot)
		{
			if (_coroutines.ContainsKey(slot))
			{
				if (_coroutines[slot] != null)
				{
					((MonoBehaviour)this).StopCoroutine(_coroutines[slot]);
				}
				_coroutines.Remove(slot);
				_durabilitySlots[slot].ResetColorRanges();
				_durabilitySlots[slot].SetValue(0f);
				SetMinimumDisplayValue(slot, -1f);
			}
		}

		public void StopAllTracking()
		{
			foreach (EquipSlots item in Enum.GetValues(typeof(EquipSlots)).Cast<EquipSlots>())
			{
				if (_coroutines.ContainsKey(item) && _coroutines[item] != null)
				{
					((MonoBehaviour)this).StopCoroutine(_coroutines[item]);
				}
			}
		}

		private void SetMinimumDisplayValue(EquipSlots slot, float minimum)
		{
			if (_displayMinimums.ContainsKey(slot))
			{
				_displayMinimums[slot] = minimum;
			}
			else
			{
				_displayMinimums.Add(slot, minimum);
			}
			RefreshDisplay();
		}

		private void OnSlotValueChanged(DurabilitySlot equipSlot)
		{
			if (_displayMinimums.TryGetValue(equipSlot.EquipmentSlot, out var value) && ((equipSlot.Value <= value && !((Behaviour)_canvas).enabled) || (equipSlot.Value > value && ((Behaviour)_canvas).enabled)))
			{
				RefreshDisplay();
			}
		}

		private void RefreshDisplay()
		{
			bool flag = _positionable?.IsPositionable ?? false;
			foreach (KeyValuePair<EquipSlots, DurabilitySlot> durabilitySlot in _durabilitySlots)
			{
				if (_displayMinimums.ContainsKey(durabilitySlot.Key) && durabilitySlot.Value.Value <= _displayMinimums[durabilitySlot.Key])
				{
					((Behaviour)durabilitySlot.Value.Image).enabled = true;
					flag = true;
				}
			}
			if (flag)
			{
				((Behaviour)LeftHand.Image).enabled = _coroutines.ContainsKey(EquipSlots.LeftHand);
				((Behaviour)RightHand.Image).enabled = _coroutines.ContainsKey(EquipSlots.RightHand);
				((Behaviour)Head.Image).enabled = true;
				((Behaviour)Chest.Image).enabled = true;
				((Behaviour)Feet.Image).enabled = true;
			}
			else
			{
				((Behaviour)Head.Image).enabled = false;
				((Behaviour)Chest.Image).enabled = false;
				((Behaviour)Feet.Image).enabled = false;
			}
			((Behaviour)_canvas).enabled = flag;
		}

		private IEnumerator SetDurabilityValue(DurabilitySlot slot, Func<float> getDurability)
		{
			while (true)
			{
				slot.SetValue(getDurability());
				yield return (object)new WaitForSeconds(1f);
			}
		}

		private IEnumerator AddToPsp()
		{
			yield return (object)new WaitUntil((Func<bool>)(() => (Object)(object)Psp.Instance != (Object)null && PlayerActionMenus.PlayerID > -1));
			UnityServicesProvider psp = Psp.Instance.GetServicesProvider(PlayerActionMenus.PlayerID);
			if (!psp.TryGetService<DurabilityDisplay>(out var _))
			{
				psp.AddSingleton(this);
			}
		}
	}
	[UnityScriptComponent]
	public class DurabilitySlot : DynamicColorImage
	{
		private Dictionary<DurableEquipmentType, Image> _equipmentImages;

		public EquipSlots EquipmentSlot;

		public DurableEquipmentType EquipmentType;

		protected override void OnAwake()
		{
			_equipmentImages = ((Component)this).GetComponentsInChildren<Image>().ToDictionary((Image i) => (DurableEquipmentType)Enum.Parse(typeof(DurableEquipmentType), ((Object)i).name, ignoreCase: true), (Image i) => i);
			SetDisplayImage(EquipmentType);
		}

		public void SetEquipmentType(DurableEquipmentType equipmentType)
		{
			EquipmentType = equipmentType;
			if (_isAwake)
			{
				SetDisplayImage(equipmentType);
			}
		}

		private void SetDisplayImage(DurableEquipmentType equipmentType)
		{
			foreach (KeyValuePair<DurableEquipmentType, Image> equipmentImage in _equipmentImages)
			{
				((Behaviour)equipmentImage.Value).enabled = equipmentImage.Key == equipmentType;
			}
			if (equipmentType != 0)
			{
				Image = _equipmentImages[equipmentType];
			}
		}
	}
	public abstract class DynamicColorImage : MonoBehaviour
	{
		public Image Image;

		protected List<ColorRange> initColorRanges = new List<ColorRange>();

		protected Dictionary<int, Color> colorMap = new Dictionary<int, Color>();

		protected bool _isAwake = false;

		protected float _value;

		public float Value => _value;

		public event Action<Color> OnColorChanged;

		public event Action<float> OnValueChanged;

		private void Awake()
		{
			ResetColorRanges();
			_isAwake = true;
			if (initColorRanges.Any())
			{
				DebugLogger.Log("Init Colors ranges found. Adding ColorMaps for image.");
				foreach (ColorRange initColorRange in initColorRanges)
				{
					AddColorMaps(initColorRange);
				}
				initColorRanges.Clear();
			}
			OnAwake();
		}

		protected abstract void OnAwake();

		public void AddColorRange(ColorRange colorRange)
		{
			if (colorRange.Min < 0f)
			{
				throw new ArgumentOutOfRangeException("Min");
			}
			if (colorRange.Max > 1f)
			{
				throw new ArgumentOutOfRangeException("Max");
			}
			if (!_isAwake)
			{
				initColorRanges.Add(colorRange);
			}
			else
			{
				AddColorMaps(colorRange);
			}
		}

		public void ResetColorRanges()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			colorMap.Clear();
			for (int i = 0; i <= 1000; i++)
			{
				colorMap.Add(i, Color.gray);
			}
		}

		public virtual void SetValue(float value)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			if (!(value < 0f) && !(value > 1f))
			{
				int key = (int)(value * 1000f);
				if (colorMap.TryGetValue(key, out var value2) && ((Graphic)Image).color != value2)
				{
					((Graphic)Image).color = value2;
					this.OnColorChanged?.Invoke(value2);
				}
				if (_value != value)
				{
					_value = value;
					this.OnValueChanged?.Invoke(_value);
				}
			}
		}

		private void AddColorMaps(ColorRange colorRange)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			int num = (int)(1000f * colorRange.Min);
			int num2 = (int)(1000f * colorRange.Max);
			for (int i = num; i <= num2; i++)
			{
				if (!colorMap.ContainsKey(i))
				{
					colorMap.Add(i, colorRange.Color);
				}
				else
				{
					colorMap[i] = colorRange.Color;
				}
			}
		}
	}
	[UnityScriptComponent]
	public class EquipmentSetMenu : MonoBehaviour, IActionMenu
	{
		private enum EquipmentSetViews
		{
			Weapons,
			Armor
		}

		public Toggle WeaponToggle;

		public Toggle ArmorToggle;

		public EquipmentSetView ArmorSetView;

		public EquipmentSetView WeaponSetView;

		private EquipmentSetViews _lastView;

		public bool IsShowing => ((Component)this).gameObject.activeSelf;

		public UnityEvent OnShow { get; } = new UnityEvent();


		public UnityEvent OnHide { get; } = new UnityEvent();


		private void Awake()
		{
			((UnityEvent<bool>)(object)WeaponToggle.onValueChanged).AddListener((UnityAction<bool>)ToggleWeaponsView);
			((UnityEvent<bool>)(object)ArmorToggle.onValueChanged).AddListener((UnityAction<bool>)ToggleArmorView);
			Hide();
		}

		public void Show()
		{
			((Component)this).gameObject.SetActive(true);
			if (WeaponToggle.isOn)
			{
				ToggleArmorView(isOn: false);
				ToggleWeaponsView(isOn: true);
			}
			else
			{
				ToggleArmorView(isOn: true);
				ToggleWeaponsView(isOn: false);
			}
			OnShow.TryInvoke();
		}

		public void Hide()
		{
			((Component)this).gameObject.SetActive(false);
			OnHide.TryInvoke();
		}

		private void ToggleWeaponsView(bool isOn)
		{
			if (isOn)
			{
				WeaponSetView.Show();
			}
			else
			{
				WeaponSetView.Hide();
			}
		}

		private void ToggleArmorView(bool isOn)
		{
			if (isOn)
			{
				ArmorSetView.Show();
			}
			else
			{
				ArmorSetView.Hide();
			}
		}
	}
	[UnityScriptComponent]
	public class EquipmentSetNameInput : MonoBehaviour
	{
		public InputField NameInput;

		public Button OkButton;

		public Text Caption;

		public Text DisplayText;

		public EquipmentSetView ParentEquipmentSet;

		public bool IsShowing => ((Component)this).gameObject.activeSelf;

		public UnityEvent OnShow { get; } = new UnityEvent();


		public UnityEvent OnHide { get; } = new UnityEvent();


		private void Awake()
		{
			Hide(raiseEvent: false);
		}

		public void Show(EquipmentSetTypes equipmentSetType, EquipSlots setIconSlot)
		{
			((Component)this).gameObject.SetActive(true);
			OnShow?.TryInvoke();
		}

		public void Show(EquipmentSetTypes equipmentSetType, string setName)
		{
			((Component)this).gameObject.SetActive(true);
			OnShow?.TryInvoke();
		}

		public void Hide()
		{
			Hide(raiseEvent: true);
		}

		private void Hide(bool raiseEvent)
		{
			((Component)this).gameObject.SetActive(false);
			if (raiseEvent)
			{
				OnHide?.TryInvoke();
			}
		}
	}
	public enum EquipmentSetTypes
	{
		Weapon,
		Armor
	}
	[UnityScriptComponent]
	public class EquipmentSetView : MonoBehaviour
	{
		public PlayerActionMenus PlayerMenu;

		public EquipmentSetTypes EquipmentSetType;

		public Dropdown EquipmentSetDropdown;

		public Button NewSetButton;

		public Button RenameSetButton;

		public Button SaveSetButton;

		public Button DeleteSetButton;

		public Dropdown EquipmentIconDropdown;

		public ActionItemView EquipmentIcon;

		public EquipmentSetNameInput SetNamePanel;

		public ConfirmationPanel ConfirmationPanel;

		private void Awake()
		{
		}

		private void Start()
		{
		}

		public void Show()
		{
			((Component)this).gameObject.SetActive(true);
		}

		public void Hide()
		{
			((Component)this).gameObject.SetActive(false);
		}

		public void Refresh()
		{
		}
	}
	[UnityScriptComponent]
	public class HotbarsContainer : MonoBehaviour
	{
		private RectTransform _leftDisplay;

		private KeyboardQuickSlotPanel _vanillaKeyboardPanel;

		private IHotbarController _controller;

		public PlayerActionMenus PlayerActionMenus;

		public List<CanvasGroup> VanillaOverlayTargets = new List<CanvasGroup>();

		public List<GameObject> VanillaSuppressionTargets = new List<GameObject>();

		private Canvas _actionBarsCanvas;

		public LeftHotbarNav LeftHotbarNav;

		private Canvas _baseHotbarCanvas;

		private GridLayoutGroup _baseGrid;

		private GridLayoutGroup[] _hotbarGrid;

		private GameObject _baseActionSlot;

		private ActionSlot[][] _hotbars;

		private Dictionary<int, ActionSlot> _actionSlots = new Dictionary<int, ActionSlot>();

		private int _selectedHotbar;

		private bool _hasChanges = false;

		public IHotbarController Controller => _controller;

		public bool HotbarsEnabled => ((Component)_actionBarsCanvas).gameObject.activeSelf;

		public Canvas ActionBarsCanvas => _actionBarsCanvas;

		internal Canvas BaseHotbarCanvas => _baseHotbarCanvas;

		internal GridLayoutGroup BaseGrid => _baseGrid;

		internal GridLayoutGroup[] HotbarGrid => _hotbarGrid;

		internal GameObject BaseActionSlot => _baseActionSlot;

		public ActionSlot[][] Hotbars => _hotbars;

		public Dictionary<int, ActionSlot> ActionSlots => _actionSlots;

		public int SelectedHotbar
		{
			get
			{
				return _selectedHotbar;
			}
			internal set
			{
				_selectedHotbar = value;
			}
		}

		public bool IsInHotkeyEditMode { get; internal set; }

		public bool IsInActionSlotEditMode { get; internal set; }

		public bool HasChanges
		{
			get
			{
				return _hasChanges;
			}
			internal set
			{
				bool hasChanges = _hasChanges;
				_hasChanges = value;
				if (value && !hasChanges)
				{
					OnHasChanges.Invoke();
				}
			}
		}

		public UnityEvent OnHasChanges { get; } = new UnityEvent();


		public bool IsAwake { get; private set; }

		public event Action OnAwake;

		public void ClearChanges()
		{
			_hasChanges = false;
		}

		private void Awake()
		{
			SetComponents();
			_controller = new HotbarsController(this);
			PlayerActionMenus.OnPlayerIdAssigned.AddListener((UnityAction<PlayerActionMenus>)OnPlayerAssigned);
			IsAwake = true;
			this.OnAwake?.Invoke();
		}

		private void OnPlayerAssigned(PlayerActionMenus menus)
		{
			if ((Object)(object)menus == (Object)(object)PlayerActionMenus)
			{
				IHotbarProfileService service = menus.ServicesProvider.GetService<IHotbarProfileService>();
				if (service != null)
				{
					service.OnProfileChanged += OnProfileChanged;
				}
			}
		}

		private void OnProfileChanged(IHotbarProfile profile, HotbarProfileChangeTypes type)
		{
			_controller.ConfigureHotbars(profile);
		}

		private void Update()
		{
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			float num = 0f;
			if (VanillaOverlayTargets != null)
			{
				foreach (CanvasGroup vanillaOverlayTarget in VanillaOverlayTargets)
				{
					if (!((Object)(object)vanillaOverlayTarget != (Object)null) || !((Component)vanillaOverlayTarget).gameObject.activeInHierarchy || !(vanillaOverlayTarget.alpha > 0.01f))
					{
						continue;
					}
					RectTransform component = ((Component)vanillaOverlayTarget).GetComponent<RectTransform>();
					if ((Object)(object)component != (Object)null)
					{
						Rect rect = component.rect;
						float num2 = ((Rect)(ref rect)).height * ((Component)vanillaOverlayTarget).transform.lossyScale.y;
						if (((Component)this).transform.lossyScale.y > 0.0001f)
						{
							num = Mathf.Max(num, num2 / ((Component)this).transform.lossyScale.y);
							continue;
						}
						float num3 = num;
						rect = component.rect;
						num = Mathf.Max(num3, ((Rect)(ref rect)).height);
					}
				}
			}
			if ((Object)(object)_vanillaKeyboardPanel == (Object)null)
			{
				_vanillaKeyboardPanel = ((Component)((Component)this).transform.root).GetComponentInChildren<KeyboardQuickSlotPanel>(true);
			}
			if ((Object)(object)_vanillaKeyboardPanel != (Object)null && ((Component)_vanillaKeyboardPanel).gameObject.activeSelf)
			{
				((Component)_vanillaKeyboardPanel).gameObject.SetActive(false);
			}
			if (VanillaSuppressionTargets != null)
			{
				for (int i = 0; i < VanillaSuppressionTargets.Count; i++)
				{
					GameObject val = VanillaSuppressionTargets[i];
					if ((Object)(object)val != (Object)null)
					{
						if (val.activeSelf)
						{
							val.SetActive(false);
						}
						if (val.transform.localScale != Vector3.zero)
						{
							val.transform.localScale = Vector3.zero;
						}
					}
				}
			}
			PositionableUI component2 = ((Component)this).GetComponent<PositionableUI>();
			if ((Object)(object)component2 != (Object)null)
			{
				component2.DynamicOffset = new Vector2(0f, num);
			}
			Controller.HotbarsContainerUpdate();
		}

		private void SetComponents()
		{
			_actionBarsCanvas = ((Component)((Component)this).transform.parent).GetComponent<Canvas>();
			LeftHotbarNav = ((Component)this).GetComponentInChildren<LeftHotbarNav>();
			_leftDisplay = ((Component)((Component)this).transform.Find("LeftDisplay")).GetComponent<RectTransform>();
			_baseHotbarCanvas = ((Component)((Component)this).transform.Find("BaseHotbarCanvas")).GetComponent<Canvas>();
			_baseGrid = ((Component)_baseHotbarCanvas).GetComponentsInChildren<GridLayoutGroup>().First((GridLayoutGroup g) => ((Object)g).name == "BaseHotbarGrid");
			_baseActionSlot = ((Component)((Component)_baseGrid).GetComponentInChildren<ActionSlot>()).gameObject;
			((Component)_baseHotbarCanvas).gameObject.SetActive(false);
			((Component)_baseGrid).gameObject.SetActive(false);
			_baseActionSlot.SetActive(false);
		}

		internal void ResetCollections()
		{
			_hotbarGrid = (GridLayoutGroup[])(object)new GridLayoutGroup[0];
			_hotbars = new ActionSlot[0][];
			_actionSlots = new Dictionary<int, ActionSlot>();
		}

		internal void Resize(float hotbarWidth, float hotbarHeight)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			RectTransform component = ((Component)this).GetComponent<RectTransform>();
			Rect rect = _leftDisplay.rect;
			component.SetSizeWithCurrentAnchors((Axis)0, hotbarWidth + ((Rect)(ref rect)).width);
			((Component)this).GetComponent<RectTransform>().SetSizeWithCurrentAnchors((Axis)1, hotbarHeight);
		}

		internal void ConfigureHotbars(int barsAmount)
		{
			_hotbarGrid = (GridLayoutGroup[])(object)new GridLayoutGroup[barsAmount];
			_hotbars = new ActionSlot[barsAmount][];
		}

		internal void ConfigureActionSlots(int bar, int slotsAmount)
		{
			_hotbars[bar] = new ActionSlot[slotsAmount];
		}
	}
	public enum AxisDirections
	{
		None,
		Up,
		Down
	}
	public class KeyGroup
	{
		public List<KeyCode> Modifiers { get; set; } = new List<KeyCode>();


		public KeyCode KeyCode { get; set; }

		public AxisDirections AxisDirection { get; set; } = AxisDirections.None;

	}
	[UnityScriptComponent]
	public class HotkeyCaptureMenu : MonoBehaviour, ISettingsView
	{
		public delegate void OnKeysSelectedDelegate(int id, HotkeyCategories category, KeyGroup keyGroup);

		public delegate void OnClearPressedDelegate(int id, HotkeyCategories category);

		public GameObject Dialog;

		public Image BackPanel;

		public Button CloseButton;

		public Button ClearButton;

		public Text CaptureHotkeyMenuText;

		public HotbarsContainer Hotbars;

		private int _slotIndex;

		private HotkeyCategories _category;

		private KeyGroup _keyGroup = new KeyGroup();

		private bool _modifierUp = false;

		private Text _text;

		private bool _monitorKeys = false;

		private bool _isInit;

		private static Dictionary<KeyCode, string> MouseButtonNames = new Dictionary<KeyCode, string>
		{
			{
				(KeyCode)323,
				"LMB"
			},
			{
				(KeyCode)324,
				"RMB"
			},
			{
				(KeyCode)325,
				"MWheel"
			},
			{
				(KeyCode)326,
				"Mouse 3"
			},
			{
				(KeyCode)327,
				"Mouse 4"
			},
			{
				(KeyCode)328,
				"Mouse 5"
			}
		};

		private bool _mouseWheelActive => _category == HotkeyCategories.NextHotbar || _category == HotkeyCategories.PreviousHotbar;

		public UnityEvent OnShow { get; } = new UnityEvent();


		public UnityEvent OnHide { get; } = new UnityEvent();


		public bool IsShowing => ((Component)this).gameObject.activeSelf && _isInit;

		public event OnKeysSelectedDelegate OnKeysSelected;

		public event OnClearPressedDelegate OnClearPressed;

		private void Awake()
		{
			DebugLogger.Log("HotkeyCaptureDialog::Awake");
			_text = ((Component)this).GetComponentsInChildren<Text>().First((Text t) => ((Object)t).name.Equals("ContentText"));
			Hide(raiseEvent: false);
			_isInit = true;
		}

		private void Start()
		{
			DebugLogger.Log("HotkeyCaptureDialog::Start");
		}

		private void Update()
		{
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			if (!_monitorKeys && IsShowing && Input.GetKeyDown((KeyCode)27))
			{
				Hide();
			}
			else
			{
				if (!_monitorKeys)
				{
					return;
				}
				PropertyInfo property = typeof(Selectable).GetProperty("currentSelectionState", BindingFlags.Instance | BindingFlags.NonPublic);
				if (IsClosedOrClear())
				{
					return;
				}
				if (Input.anyKeyDown)
				{
					if (Input.GetKeyDown((KeyCode)27))
					{
						HideDialog();
						return;
					}
					foreach (KeyCode item in Enum.GetValues(typeof(KeyCode)).Cast<KeyCode>())
					{
						if (Input.GetKeyDown(item) && _keyGroup.KeyCode != item && !_keyGroup.Modifiers.Contains(item))
						{
							AddKeyCode(item);
							break;
						}
					}
				}
				if (Input.mouseScrollDelta.y > 0f && _mouseWheelActive)
				{
					AddKeyCode((KeyCode)325, AxisDirections.Up);
				}
				else if (Input.mouseScrollDelta.y < 0f && _mouseWheelActive)
				{
					AddKeyCode((KeyCode)325, AxisDirections.Down);
				}
				for (int i = 0; i < _keyGroup.Modifiers.Count; i++)
				{
					if (Input.GetKeyUp(_keyGroup.Modifiers[i]))
					{
						_modifierUp = true;
						break;
					}
				}
				if (Input.GetKeyUp(_keyGroup.KeyCode) || (_modifierUp && (int)_keyGroup.KeyCode != 0) || (!Mathf.Approximately(Input.mouseScrollDelta.y, 0f) && _mouseWheelActive))
				{
					try
					{
						this.OnKeysSelected?.Invoke(_slotIndex, _category, _keyGroup);
						Hotbars.Controller.ToggleHotkeyEdits(enabled: true);
					}
					catch (Exception ex)
					{
						Debug.LogException(ex);
					}
					HideDialog();
				}
			}
		}

		private bool IsClosedOrClear()
		{
			return ((Selectable)(object)ClearButton).GetSelectionState() == SelectableExtensions.SelectionState.Selected || ((Selectable)(object)ClearButton).GetSelectionState() == SelectableExtensions.SelectionState.Highlighted || ((Selectable)(object)ClearButton).GetSelectionState() == SelectableExtensions.SelectionState.Pressed || ((Selectable)(object)CloseButton).GetSelectionState() == SelectableExtensions.SelectionState.Selected || ((Selectable)(object)CloseButton).GetSelectionState() == SelectableExtensions.SelectionState.Highlighted || ((Selectable)(object)CloseButton).GetSelectionState() == SelectableExtensions.SelectionState.Pressed;
		}

		private void AddKeyCode(KeyCode key, AxisDirections axis = AxisDirections.None)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Invalid comparison between Unknown and I4
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Expected I4, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected I4, but got Unknown
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Invalid comparison between Unknown and I4
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			if (!string.IsNullOrWhiteSpace(_text.text))
			{
				Text text = _text;
				text.text += "+";
			}
			KeyCode val = key;
			KeyCode val2 = val;
			if (val2 - 48 > 9)
			{
				switch (val2 - 303)
				{
				case 4:
				case 5:
				{
					_keyGroup.Modifiers = new List<KeyCode>
					{
						(KeyCode)307,
						(KeyCode)308
					};
					Text text4 = _text;
					text4.text += "Alt";
					return;
				}
				case 2:
				case 3:
				{
					_keyGroup.Modifiers = new List<KeyCode>
					{
						(KeyCode)305,
						(KeyCode)306
					};
					Text text3 = _text;
					text3.text += "Ctrl";
					return;
				}
				case 0:
				case 1:
				{
					_keyGroup.Modifiers = new List<KeyCode>
					{
						(KeyCode)303,
						(KeyCode)304
					};
					Text text2 = _text;
					text2.text += "Shift";
					return;
				}
				}
				if (val2 - 323 <= 6)
				{
					_keyGroup.Modifiers.Clear();
					_keyGroup.KeyCode = key;
					_keyGroup.AxisDirection = axis;
					_text.text = MouseButtonNames[key];
					if (axis != 0)
					{
						_text.text = "MW_" + axis;
					}
				}
				else
				{
					_keyGroup.KeyCode = key;
					Text text5 = _text;
					text5.text += ((object)(KeyCode)(ref key)).ToString();
				}
			}
			else
			{
				_keyGroup.KeyCode = key;
				Text text6 = _text;
				text6.text += key - 48;
			}
		}

		public void ClearPressed()
		{
			this.OnClearPressed?.Invoke(_slotIndex, _category);
			this.OnKeysSelected?.Invoke(_slotIndex, _category, new KeyGroup
			{
				KeyCode = (KeyCode)0
			});
			Hotbars.Controller.ToggleHotkeyEdits(enabled: true);
			HideDialog();
		}

		public void Show()
		{
			((Component)this).gameObject.SetActive(true);
			((Component)BackPanel).gameObject.SetActive(true);
			((Component)CaptureHotkeyMenuText).gameObject.SetActive(true);
			Dialog.SetActive(false);
			Hotbars.Controller.ToggleHotkeyEdits(enabled: true);
			OnShow?.TryInvoke();
		}

		public void ShowDialog(int slotIndex, HotkeyCategories category)
		{
			DebugLogger.Log($"Capturing Hotkey for slot index {slotIndex} in category {category}.");
			_modifierUp = false;
			_keyGroup.KeyCode = (KeyCode)0;
			_keyGroup.Modifiers.Clear();
			_keyGroup.AxisDirection = AxisDirections.None;
			_text.text = string.Empty;
			_slotIndex = slotIndex;
			_category = category;
			Dialog.SetActive(true);
			_monitorKeys = true;
		}

		public void HideDialog()
		{
			_slotIndex = 0;
			_modifierUp = false;
			_category = HotkeyCategories.None;
			_text.text = string.Empty;
			_keyGroup.KeyCode = (KeyCode)0;
			_keyGroup.Modifiers.Clear();
			Dialog.SetActive(false);
			_monitorKeys = false;
		}

		public void Hide()
		{
			Hide(raiseEvent: true);
		}

		private void Hide(bool raiseEvent)
		{
			Hotbars.Controller?.ToggleHotkeyEdits(enabled: false);
			if (_isInit)
			{
				HideDialog();
			}
			((Component)this).gameObject.SetActive(false);
			((Component)BackPanel).gameObject.SetActive(false);
			((Component)CaptureHotkeyMenuText).gameObject.SetActive(false);
			if (raiseEvent)
			{
				OnHide?.TryInvoke();
			}
		}

		private bool IsModifier(KeyCode keyCode)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			if (keyCode - 303 <= 5)
			{
				return true;
			}
			return false;
		}
	}
	[UnityScriptComponent]
	public class LeftHotbarNav : MonoBehaviour
	{
		public PlayerActionMenus PlayerMenu;

		public HotbarsContainer HotbarsContainer;

		private Button _nextButton;

		private Button _nextHotkeyButton;

		private Button _previousButton;

		private Button _previousHotkeyButton;

		private Text _barText;

		private Text _nextHotkeyText;

		private Text _previousHotkeyText;

		private GameObject _barHotkeyGo;

		private Button _hotkeyButton;

		private Text _hotkeyText;

		private List<string> _hotbarHotkeys = new List<string>();

		private Canvas _leftNavCanvas;

		private bool _isHidden;

		private bool _awake = false;

		private bool _inEditMode;

		private bool _inHotkeyEditMode;

		public bool InEditMode => _inEditMode;

		public bool InHotkeyEditMode => _inHotkeyEditMode;

		private IHotbarNavActions GetHotbarNavActions()
		{
			UnityServicesProvider unityServicesProvider = Psp.Instance?.GetServicesProvider(PlayerMenu.PlayerID);
			if (unityServicesProvider != null && unityServicesProvider.TryGetService<IHotbarNavActions>(out var service))
			{
				return service;
			}
			return null;
		}

		private void Awake()
		{
			SetComponents();
			SetBarText(string.Empty);
			SetNextHotkeyText(string.Empty);
			SetPreviousHotkeyText(string.Empty);
			SetHotkeyText(string.Empty);
			HookButtonEvents();
			_awake = true;
			ToggleActionSlotEditMode(enableEdits: false);
			ToggleHotkeyEditMode(enableEdits: false);
		}

		private void Update()
		{
			if (_inHotkeyEditMode || _inEditMode)
			{
				return;
			}
			IHotbarNavActions hotbarNavActions = GetHotbarNavActions();
			if (hotbarNavActions != null)
			{
				int hotbarIndex;
				if (hotbarNavActions.IsNextRequested())
				{
					HotbarsContainer.Controller.SelectNext();
				}
				else if (hotbarNavActions.IsPreviousRequested())
				{
					HotbarsContainer.Controller.SelectPrevious();
				}
				else if (hotbarNavActions.IsHotbarRequested(out hotbarIndex))
				{
					HotbarsContainer.Controller.SelectHotbar(hotbarIndex);
				}
			}
		}

		private void SetComponents()
		{
			GameObject gameObject = ((Component)((Component)this).transform.Find("BarNumber/NextHotbar")).gameObject;
			_nextButton = gameObject.GetComponentsInChildren<Button>().First((Button b) => ((Object)b).name.Equals("NextButton"));
			_nextHotkeyButton = gameObject.GetComponentsInChildren<Button>().First((Button b) => ((Object)b).name.Equals("HotkeyButton"));
			_nextHotkeyText = gameObject.GetComponentInChildren<Text>();
			GameObject gameObject2 = ((Component)((Component)this).transform.Find("BarNumber/PreviousHotbar")).gameObject;
			_previousButton = gameObject2.GetComponentsInChildren<Button>().First((Button b) => ((Object)b).name.Equals("PreviousButton"));
			_previousHotkeyButton = gameObject2.GetComponentsInChildren<Button>().First((Button b) => ((Object)b).name.Equals("HotkeyButton"));
			_previousHotkeyText = gameObject2.GetComponentInChildren<Text>();
			_barHotkeyGo = ((Component)((Component)this).transform.Find("BarNumber/BarHotkey")).gameObject;
			_hotkeyButton = _barHotkeyGo.GetComponentsInChildren<Button>().First((Button b) => ((Object)b).name.Equals("HotkeyButton"));
			_hotkeyText = _barHotkeyGo.GetComponentInChildren<Text>();
			GameObject gameObject3 = ((Component)((Component)this).transform.Find("BarNumber/BarIcon")).gameObject;
			_barText = gameObject3.GetComponentInChildren<Text>();
			_leftNavCanvas = ((Component)this).GetComponent<Canvas>();
		}

		public void Show()
		{
			_isHidden = false;
			((Behaviour)_leftNavCanvas).enabled = true;
		}

		public void Hide()
		{
			_isHidden = true;
			((Behaviour)_leftNavCanvas).enabled = false;
		}

		public void SetBarText(string text)
		{
			_barText.text = text;
		}

		public void SetNextHotkeyText(string text)
		{
			_nextHotkeyText.text = text;
		}

		public void SetPreviousHotkeyText(string text)
		{
			_previousHotkeyText.text = text;
		}

		public void SetHotkeyText(string text)
		{
			_hotkeyText.text = text;
			if (string.IsNullOrWhiteSpace(text) && _barHotkeyGo.activeSelf && !_inEditMode)
			{
				_barHotkeyGo.SetActive(false);
			}
			else if (!string.IsNullOrWhiteSpace(text) && !_barHotkeyGo.activeSelf)
			{
				_barHotkeyGo.SetActive(true);
			}
		}

		public void SetHotkeys(IEnumerable<string> hotbarTexts)
		{
			_hotbarHotkeys = hotbarTexts.ToList();
		}

		public void SelectHotbar(int barIndex)
		{
			_barText.text = (barIndex + 1).ToString();
			List<string> hotbarHotkeys = _hotbarHotkeys;
			SetHotkeyText((hotbarHotkeys != null && hotbarHotkeys.Count > barIndex) ? _hotbarHotkeys[barIndex] : string.Empty);
		}

		public void ToggleActionSlotEditMode(bool enableEdits)
		{
			if (_awake)
			{
				_inEditMode = enableEdits;
				((Component)_nextButton).gameObject.SetActive(enableEdits);
				((Component)_previousButton).gameObject.SetActive(enableEdits);
				ToggleShowHide(enableEdits);
			}
		}

		public void ToggleHotkeyEditMode(bool enableEdits)
		{
			if (!_awake)
			{
				return;
			}
			_inHotkeyEditMode = enableEdits;
			Button nextHotkeyButton = _nextHotkeyButton;
			if (nextHotkeyButton != null)
			{
				GameObject gameObject = ((Component)nextHotkeyButton).gameObject;
				if (gameObject != null)
				{
					gameObject.SetActive(enableEdits);
				}
			}
			Button previousHotkeyButton = _previousHotkeyButton;
			if (previousHotkeyButton != null)
			{
				GameObject gameObject2 = ((Component)previousHotkeyButton).gameObject;
				if (gameObject2 != null)
				{
					gameObject2.SetActive(enableEdits);
				}
			}
			Button hotkeyButton = _hotkeyButton;
			if (hotkeyButton != null)
			{
				GameObject gameObject3 = ((Component)hotkeyButton).gameObject;
				if (gameObject3 != null)
				{
					gameObject3.SetActive(enableEdits);
				}
			}
			if (enableEdits)
			{
				GameObject barHotkeyGo = _barHotkeyGo;
				if (barHotkeyGo != null)
				{
					barHotkeyGo.SetActive(true);
				}
			}
			else if (!enableEdits)
			{
				Text hotkeyText = _hotkeyText;
				if (string.IsNullOrWhiteSpace((hotkeyText != null) ? hotkeyText.text : null))
				{
					GameObject barHotkeyGo2 = _barHotkeyGo;
					if (barHotkeyGo2 != null)
					{
						barHotkeyGo2.SetActive(false);
					}
				}
			}
			ToggleShowHide(enableEdits);
		}

		private void ToggleShowHide(bool editsEnabled)
		{
			if (editsEnabled)
			{
				((Behaviour)_leftNavCanvas).enabled = true;
			}
			else if (!editsEnabled && _isHidden)
			{
				((Behaviour)_leftNavCanvas).enabled = false;
			}
		}

		private void HookButtonEvents()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Expected O, but got Unknown
			((UnityEvent)_nextButton.onClick).AddListener((UnityAction)delegate
			{
				HotbarsContainer.Controller.SelectNext();
			});
			((UnityEvent)_previousButton.onClick).AddListener((UnityAction)delegate
			{
				HotbarsContainer.Controller.SelectPrevious();
			});
			((UnityEvent)_nextHotkeyButton.onClick).AddListener((UnityAction)delegate
			{
				PlayerMenu.MainSettingsMenu.HotkeyCaptureMenu.ShowDialog(0, HotkeyCategories.NextHotbar);
			});
			((UnityEvent)_previousHotkeyButton.onClick).AddListener((UnityAction)delegate
			{
				PlayerMenu.MainSettingsMenu.HotkeyCaptureMenu.ShowDialog(1, HotkeyCategories.PreviousHotbar);
			});
			((UnityEvent)_hotkeyButton.onClick).AddListener((UnityAction)delegate
			{
				PlayerMenu.MainSettingsMenu.HotkeyCaptureMenu.ShowDialog(HotbarsContainer.SelectedHotbar, HotkeyCategories.Hotbar);
			});
		}
	}
	public enum ActionSettingsMenus
	{
		Settings,
		ActionSlots,
		EquipmentSets,
		ProfileName,
		HotkeyCapture,
		UIPosition,
		Stash
	}
	[UnityScriptComponent]
	public class MainSettingsMenu : MonoBehaviour, IActionMenu
	{
		public PlayerActionMenus PlayerMenu;

		public SettingsView SettingsView;

		public HotbarSettingsView HotbarSettingsView;

		public HotkeyCaptureMenu HotkeyCaptureMenu;

		public UIPositionScreen UIPositionScreen;

		public EquipmentSetsSettingsView EquipmentSetsSettingsView;

		public StorageSettingsView StorageSettingsView;

		public Toggle SettingsViewToggle;

		public Toggle HotbarViewToggle;

		public Toggle EquipmentSetViewToggle;

		public Toggle StashViewToggle;

		private Dictionary<ActionSettingsMenus, ISettingsView> _menus;

		private Dictionary<ActionSettingsMenus, ISettingsView> _settingsViews;

		private SelectableTransitions[] _selectables;

		private bool _isInit;

		public bool IsShowing => ((Component)this).gameObject.activeSelf || HotkeyCaptureMenu.IsShowing || UIPositionScreen.IsShowing;

		public UnityEvent OnShow { get; } = new UnityEvent();


		public UnityEvent OnHide { get; } = new UnityEvent();


		public bool MenuItemSelected => _selectables != null && _selectables.Any((SelectableTransitions s) => s.Selected);

		private void Awake()
		{
			DebugLogger.Log("MainSettingsMenu::Awake");
			_menus = new Dictionary<ActionSettingsMenus, ISettingsView>();
			_menus.Add(ActionSettingsMenus.Settings, SettingsView);
			_menus.Add(ActionSettingsMenus.ActionSlots, HotbarSettingsView);
			_menus.Add(ActionSettingsMenus.EquipmentSets, EquipmentSetsSettingsView);
			_menus.Add(ActionSettingsMenus.HotkeyCapture, HotkeyCaptureMenu);
			_menus.Add(ActionSettingsMenus.UIPosition, UIPositionScreen);
			_menus.Add(ActionSettingsMenus.Stash, StorageSettingsView);
			_settingsViews = new Dictionary<ActionSettingsMenus, ISettingsView>
			{
				{
					ActionSettingsMenus.Settings,
					SettingsView
				},
				{
					ActionSettingsMenus.ActionSlots,
					HotbarSettingsView
				},
				{
					ActionSettingsMenus.EquipmentSets,
					EquipmentSetsSettingsView
				},
				{
					ActionSettingsMenus.Stash,
					StorageSettingsView
				}
			};
			((UnityEvent<bool>)(object)SettingsViewToggle.onValueChanged).AddListener((UnityAction<bool>)delegate
			{
				ShowMenu(ActionSettingsMenus.Settings);
			});
			((UnityEvent<bool>)(object)HotbarViewToggle.onValueChanged).AddListener((UnityAction<bool>)delegate
			{
				ShowMenu(ActionSettingsMenus.ActionSlots);
			});
			((UnityEvent<bool>)(object)EquipmentSetViewToggle.onValueChanged).AddListener((UnityAction<bool>)delegate
			{
				ShowMenu(ActionSettingsMenus.EquipmentSets);
			});
			((UnityEvent<bool>)(object)StashViewToggle.onValueChanged).AddListener((UnityAction<bool>)delegate
			{
				ShowMenu(ActionSettingsMenus.Stash);
			});
			_selectables = ((Component)this).GetComponentsInChildren<SelectableTransitions>();
		}

		private void Start()
		{
			DebugLogger.Log("MainSettingsMenu::Start");
			if (!_isInit)
			{
				Hide(raiseEvent: false);
			}
			_isInit = true;
		}

		public void Show()
		{
			DebugLogger.Log("MainSettingsMenu::Show");
			((Component)this).gameObject.SetActive(true);
			OnShow?.TryInvoke();
			if (HotbarViewToggle.isOn)
			{
				ShowMenu(ActionSettingsMenus.ActionSlots);
			}
			else if (EquipmentSetViewToggle.isOn)
			{
				ShowMenu(ActionSettingsMenus.EquipmentSets);
			}
			else if (StashViewToggle.isOn)
			{
				ShowMenu(ActionSettingsMenus.Stash);
			}
			else
			{
				ShowMenu(ActionSettingsMenus.Settings);
			}
		}

		public void Hide()
		{
			Hide(raiseEvent: true);
		}

		private void Hide(bool raiseEvent)
		{
			DebugLogger.Log("MainSettingsMenu::Hide");
			IEnumerable<ISettingsView> enumerable = from kvp in _menus
				where kvp.Value.IsShowing && !_settingsViews.ContainsKey(kvp.Key)
				select kvp.Value;
			bool flag = false;
			foreach (ISettingsView item in enumerable)
			{
				item.Hide();
				flag = true;
			}
			DebugLogger.Log($"MainSettingsMenu::Hide: hideMenus.Count == {enumerable?.Count()}");
			if (!flag && ((Component)this).gameObject.activeSelf)
			{
				DebugLogger.Log("MainSettingsMenu::Hide: SetActive(false)");
				((Component)this).gameObject.SetActive(false);
				if (raiseEvent)
				{
					OnHide?.TryInvoke();
				}
			}
		}

		public void ShowMenu(ActionSettingsMenus menuType)
		{
			_menus[menuType].Show();
			IEnumerable<ISettingsView> enumerable = from kvp in _menus
				where kvp.Key != menuType
				select kvp.Value;
			foreach (ISettingsView item in enumerable)
			{
				try
				{
					item.Hide();
				}
				catch (Exception ex)
				{
					Debug.LogError((object)$"Failed to hide menu type {menuType}. Disabling menu.");
					Debug.LogException(ex);
					MonoBehaviour val = (MonoBehaviour)((item is MonoBehaviour) ? item : null);
					if (val != null)
					{
						((Component)val).gameObject.SetActive(false);
					}
				}
			}
		}
	}
	[UnityScriptComponent]
	public class MouseClickListener : MonoBehaviour, IPointerClickHandler, IEventSystemHandler
	{
		public UnityEvent OnLeftClick;

		public UnityEvent OnRightClick;

		public UnityEvent OnMiddleClick;

		public void OnPointerClick(PointerEventData eventData)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Invalid comparison between Unknown and I4
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Invalid comparison between Unknown and I4
			if ((int)eventData.button == 0)
			{
				OnLeftClick.Invoke();
			}
			else if ((int)eventData.button == 1)
			{
				OnRightClick.Invoke();
			}
			else if ((int)eventData.button == 2)
			{
				OnMiddleClick.Invoke();
			}
		}
	}
	[UnityScriptComponent]
	public class PlayerActionMenus : MonoBehaviour
	{
		private int _playerID = -1;

		public MainSettingsMenu MainSettingsMenu;

		public DurabilityDisplay DurabilityDisplay;

		public EquipmentSetMenu EquipmentSetMenus;

		public ActionsViewer ActionsViewer;

		private UnityServicesProvider _servicesProvider;

		private IActionMenu[] _actionMenus;

		private MenuNavigationActions _navActions;

		private bool _isAwake = false;

		private bool _isPlayerAssigned = false;

		private static readonly UnityEvent<PlayerActionMenus> _onPlayerIdAssigned = new UnityEvent<PlayerActionMenus>();

		public int PlayerID => _playerID;

		public UnityServicesProvider ServicesProvider => _servicesProvider;

		public MenuNavigationActions NavActions => _navActions;

		public bool IsPlayerAssigned => _isPlayerAssigned;

		public static UnityEvent<PlayerActionMenus> OnPlayerIdAssigned => _onPlayerIdAssigned;

		public void SetIDs(int playerID)
		{
			_playerID = playerID;
			_servicesProvider = Psp.Instance.GetServicesProvider(playerID);
			IPositionsProfileService service = _servicesProvider.GetService<IPositionsProfileService>();
			PositionableUI[] positionableUIs = GetPositionableUIs();
			PositionableUI[] array = positionableUIs;
			foreach (PositionableUI positionableUI in array)
			{
				positionableUI.SetPositionsService(service);
			}
			_isPlayerAssigned = true;
			_onPlayerIdAssigned.Invoke(this);
		}

		public PositionableUI[] GetPositionableUIs()
		{
			return ((Component)((Component)this).transform.parent).GetComponentsInChildren<PositionableUI>(true);
		}

		private void Awake()
		{
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Expected O, but got Unknown
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Expected O, but got Unknown
			Transform[] componentsInChildren = ((Component)this).GetComponentsInChildren<Transform>(true);
			Transform[] array = componentsInChildren;
			foreach (Transform val in array)
			{
				if ((Object)(object)val != (Object)null && (Object)(object)((Component)val).gameObject != (Object)null && ((Object)val).name.Contains("SkillChain"))
				{
					DebugLogger.Log("Destroying persistent SkillChain object: " + ((Object)val).name);
					Object.Destroy((Object)(object)((Component)val).gameObject);
				}
			}
			_actionMenus = ((Component)this).GetComponentsInChildren<IActionMenu>(true);
			for (int j = 0; j < _actionMenus.Length; j++)
			{
				DebugLogger.Log($"_actionMenus[{j}] == null == {_actionMenus[j] == null}. _actionMenus[{j}].OnShow == null == {_actionMenus[j]?.OnShow == null}");
				int menuIndex = j;
				_actionMenus[j].OnShow.AddListener((UnityAction)delegate
				{
					OnShowMenu(menuIndex);
				});
				_actionMenus[j].OnHide.AddListener(new UnityAction(OnHideMenu));
			}
			_isAwake = true;
		}

		private void Update()
		{
			if (_navActions == null)
			{
				return;
			}
			Func<bool> cancel = _navActions.Cancel;
			if (cancel == null || !cancel())
			{
				return;
			}
			for (int i = 0; i < _actionMenus.Length; i++)
			{
				if (_actionMenus[i].IsShowing)
				{
					_actionMenus[i].Hide();
				}
			}
		}

		public void ConfigureNavigation(MenuNavigationActions navActions)
		{
			_navActions = navActions;
		}

		public bool AnyActionMenuShowing()
		{
			return _isAwake && _actionMenus.Any((IActionMenu m) => m.IsShowing);
		}

		private void OnShowMenu(int menuIndex)
		{
			for (int i = 0; i < _actionMenus.Length; i++)
			{
				if (i != menuIndex && _actionMenus[i].IsShowing)
				{
					_actionMenus[i].Hide();
				}
			}
		}

		private void OnHideMenu()
		{
		}
	}
	[UnityScriptComponent]
	public class PositionableUI : MonoBehaviour, IDragHandler, IEventSystemHandler, IBeginDragHandler, IEndDragHandler
	{
		public Image BackgroundImage;

		public Button ResetButton;

		private UIPosition _originPosition;

		private bool _positioningEnabled = false;

		private IPositionsProfileService _positionsProfileService;

		private bool profileChangeEventNeeded = false;

		private bool _buttonInit;

		private bool _raycasterAdded;

		private bool _canvasAdded;

		private Vector2 _startPosition;

		private bool _startPositionSet;

		private Vector2 _logicalPosition;

		private bool _logicalPositionInit = false;

		private Vector2 _offset;

		public string TransformPath => ((Component)this).transform.GetPath();

		public string NormalizedTransformPath => ((Component)this).transform.GetNormalizedPath();

		public RectTransform RectTransform => ((Component)this).GetComponent<RectTransform>();

		public UIPosition OriginPosition => _originPosition;

		public bool HasMoved => _startPositionSet && (!Mathf.Approximately(StartPosition.x, RectTransform.anchoredPosition.x) || !Mathf.Approximately(StartPosition.y, RectTransform.anchoredPosition.y));

		public UnityEvent<bool> OnIsPositionableChanged { get; private set; } = new UnityEvent<bool>();


		public bool IsPositionable => _positioningEnabled;

		public Vector2 StartPosition
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				return _startPosition;
			}
			private set
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0003: Unknown result type (might be due to invalid IL or missing references)
				_startPosition = value;
				_startPositionSet = true;
			}
		}

		public Vector2 DynamicOffset { get; set; } = Vector2.zero;


		public UnityEvent<PositionableUI> UIElementMoved { get; } = new UnityEvent<PositionableUI>();


		private void InitializeLogicalPosition()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if (!_logicalPositionInit)
			{
				_logicalPosition = RectTransform.anchoredPosition;
				_logicalPositionInit = true;
			}
		}

		private void Start()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			InitializeLogicalPosition();
			if ((Object)(object)ResetButton != (Object)null && !_buttonInit)
			{
				((UnityEvent)ResetButton.onClick).AddListener(new UnityAction(ResetToOrigin));
				_buttonInit = true;
			}
			if (_originPosition == null)
			{
				_originPosition = RectTransform.ToRectTransformPosition();
			}
			StartPosition = new Vector2(RectTransform.anchoredPosition.x, RectTransform.anchoredPosition.y);
			_logicalPosition = StartPosition;
			if (_positionsProfileService != null)
			{
				SetPositionFromProfile(_positionsProfileService.GetProfile());
			}
			if ((Object)(object)BackgroundImage != (Object)null)
			{
				((Component)BackgroundImage).gameObject.SetActive(_positioningEnabled);
			}
		}

		private void Update()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			if (_logicalPositionInit)
			{
				RectTransform.anchoredPosition = _logicalPosition + DynamicOffset;
			}
			if (profileChangeEventNeeded && _positionsProfileService != null)
			{
				profileChangeEventNeeded = false;
				DebugLogger.Log("[Debug  :ActionMenus] PositionableUI{" + ((Object)this).name + "}::Update: Adding OnProfileChanged listener.");
				_positionsProfileService.OnProfileChanged += OnProfileChanged;
			}
		}

		public void SetPositionsService(IPositionsProfileService positionsProfileService)
		{
			_positionsProfileService = positionsProfileService;
			profileChangeEventNeeded = true;
			if (_positionsProfileService != null)
			{
				DebugLogger.Log("[Debug  :ActionMenus] PositionableUI{" + ((Object)this).name + "}::SetPositionsService: Adding OnProfileChanged listener.");
				_positionsProfileService.OnProfileChanged += OnProfileChanged;
				profileChangeEventNeeded = false;
				SetPositionFromProfile(_positionsProfileService.GetProfile());
			}
		}

		public void EnableMovement()
		{
			_positioningEnabled = true;
			if ((Object)(object)BackgroundImage != (Object)null)
			{
				((Component)BackgroundImage).gameObject.SetActive(_positioningEnabled);
			}
			Canvas component = ((Component)this).gameObject.GetComponent<Canvas>();
			if ((Object)(object)component == (Object)null)
			{
				((Component)this).gameObject.AddComponent<Canvas>();
				_canvasAdded = true;
			}
			GraphicRaycaster component2 = ((Component)this).GetComponent<GraphicRaycaster>();
			if ((Object)(object)component == (Object)null)
			{
				((Component)this).gameObject.AddComponent<GraphicRaycaster>();
				_raycasterAdded = true;
			}
			OnIsPositionableChanged.Invoke(_positioningEnabled);
		}

		public void DisableMovement()
		{
			_positioningEnabled = false;
			if ((Object)(object)BackgroundImage != (Object)null)
			{
				((Component)BackgroundImage).gameObject.SetActive(_positioningEnabled);
			}
			if (_raycasterAdded)
			{
				GraphicRaycaster component = ((Component)this).GetComponent<GraphicRaycaster>();
				if ((Object)(object)component != (Object)null)
				{
					Object.Destroy((Object)(object)component);
				}
				_raycasterAdded = false;
			}
			if (_canvasAdded)
			{
				Canvas component2 = ((Component)this).gameObject.GetComponent<Canvas>();
				if ((Object)(object)component2 != (Object)null)
				{
					Object.Destroy((Object)(object)component2);
				}
				_canvasAdded = false;
			}
			OnIsPositionableChanged.Invoke(_positioningEnabled);
		}

		public void SetPosition(float x, float y)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			InitializeLogicalPosition();
			_logicalPosition = new Vector2(x, y);
			RectTransform.anchoredPosition = _logicalPosition + DynamicOffset;
		}

		public void SetPosition(UIPosition position)
		{
			SetPosition(position.AnchoredPosition.X, position.AnchoredPosition.Y);
		}

		public void SetPositionFromProfile(PositionsProfile profile)
		{
			string normalizedPath = NormalizedTransformPath;
			UIPositions uIPositions = profile.Positions?.FirstOrDefault((UIPositions p) => TransformExtensions.NormalizePath(p.TransformPath) == normalizedPath);
			if (uIPositions != null)
			{
				DebugLogger.Log($"[Debug  :ActionMenus] PositionableUI{{{((Object)this).name}}}: Setting position of PositionableUI {((Object)this).name} to modified position of ({uIPositions.ModifiedPosition.AnchoredPosition.X}, {uIPositions.ModifiedPosition.AnchoredPosition.Y}).");
				SetPosition(uIPositions.ModifiedPosition);
				_originPosition = uIPositions.OriginPosition;
			}
		}

		private void OnProfileChanged(PositionsProfile profile)
		{
			DebugLogger.Log("[Debug  :ActionMenus] PositionableUI{" + ((Object)this).name + "}: OnProfileChanged for PositionableUI " + ((Object)this).name + ".");
			ResetToOrigin();
			SetPositionFromProfile(profile);
		}

		public void ResetToOrigin()
		{
			if (_originPosition != null)
			{
				DebugLogger.Log($"[Debug  :ActionMenus] PositionableUI{{{((Object)this).name}}}: Setting position of PositionableUI {((Object)this).name} to origin position of ({_originPosition.AnchoredPosition.X}, {_originPosition.AnchoredPosition.Y}).");
				SetPosition(_originPosition);
			}
		}

		public void OnDrag(PointerEventData eventData)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			if (_positioningEnabled)
			{
				((Component)this).transform.position = Vector2.op_Implicit(new Vector2(Input.mousePosition.x, Input.mousePosition.y) - _offset);
				_logicalPosition = RectTransform.anchoredPosition - DynamicOffset;
			}
		}

		public void OnBeginDrag(PointerEventData eventData)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			if (_positioningEnabled)
			{
				DebugLogger.Log("Dragging started.");
				if (_originPosition == null)
				{
					_originPosition = RectTransform.ToRectTransformPosition();
				}
				InitializeLogicalPosition();
				StartPosition = _logicalPosition;
				_offset = eventData.position - new Vector2(((Transform)RectTransform).position.x, ((Transform)RectTransform).position.y);
			}
		}

		public void OnEndDrag(PointerEventData eventData)
		{
			if (_positioningEnabled)
			{
				if (HasMoved)
				{
					UIElementMoved?.TryInvoke(this);
				}
				DebugLogger.Log("Dragging Done.");
			}
		}

		public UIPositions GetUIPositions()
		{
			return new UIPositions
			{
				ModifiedPosition = RectTransform.ToRectTransformPosition(),
				OriginPosition = _originPosition,
				TransformPath = ((Component)this).transform.GetNormalizedPath()
			};
		}
	}
	[UnityScriptComponent]
	public class ProgressBar : DynamicColorImage
	{
		public Image Frame;

		public override void SetValue(float value)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			base.SetValue(value);
			if (((Graphic)Image).color != ((Graphic)Frame).color)
			{
				((Graphic)Frame).color = ((Graphic)Image).color;
			}
			Image.fillAmount = value;
		}

		protected override void OnAwake()
		{
		}
	}
	[UnityScriptComponent]
	public class Psp : MonoBehaviour
	{
		private ConcurrentDictionary<int, UnityServicesProvider> services;

		public static Psp Instance { get; private set; }

		private void Awake()
		{
			Instance = this;
			services = new ConcurrentDictionary<int, UnityServicesProvider>();
		}

		public UnityServicesProvider GetServicesProvider(int playerId)
		{
			return services.GetOrAdd(playerId, new UnityServicesProvider());
		}

		public bool TryGetServicesProvider(int playerId, out UnityServicesProvider usp)
		{
			return services.TryGetValue(playerId, out usp);
		}

		public bool TryDisposeServicesProvider(int playerId)
		{
			if (services.TryGetValue(playerId, out var value))
			{
				try
				{
					value.Dispose();
				}
				catch (Exception ex)
				{
					Debug.LogError((object)string.Format("ActionUI: Dispose of {0} for playerID {1} failed.", "UnityServicesProvider", playerId));
					Debug.LogException(ex);
				}
			}
			UnityServicesProvider value2;
			return services.TryRemove(playerId, out value2);
		}
	}
	[UnityScriptComponent]
	public class SelectableTransitions : MonoBehaviour, ISelectHandler, IEventSystemHandler, IDeselectHandler
	{
		public Image SelectImage;

		private Selectable _selectable;

		private bool _selected;

		public Selectable Selectable => _selectable;

		public SelectableExtensions.SelectionState SelectionState => _selectable?.GetSelectionState() ?? SelectableExtensions.SelectionState.Normal;

		public bool Selected => _selected;

		public event Action<SelectableTransitions> OnSelected;

		public event Action<SelectableTransitions> OnDeselected;

		private void Awake()
		{
			_selectable = ((Component)this).GetComponent<Selectable>();
		}

		private void Start()
		{
			if ((Object)(object)SelectImage != (Object)null)
			{
				((Behaviour)SelectImage).enabled = _selected;
			}
		}

		public void OnSelect(BaseEventData eventData)
		{
			if ((Object)(object)SelectImage != (Object)null)
			{
				((Behaviour)SelectImage).enabled = true;
			}
			_selected = true;
			this.OnSelected?.Invoke(this);
		}

		public void OnDeselect(BaseEventData eventData)
		{
			if ((Object)(object)SelectImage != (Object)null)
			{
				((Behaviour)SelectImage).enabled = false;
			}
			_selected = false;
			this.OnDeselected?.Invoke(this);
		}
	}
	[UnityScriptComponent]
	public class EquipmentSetsSettingsView : MonoBehaviour, ISettingsView
	{
		public Toggle ArmorSetsCombat;

		public Toggle SkipWeaponAnimation;

		public Toggle EquipFromStash;

		public Toggle StashEquipAnywhere;

		public Toggle UnequipToStash;

		public Toggle StashUnequipAnywhere;

		public MainSettingsMenu MainSettingsMenu;

		public bool IsShowing => ((Component)this).gameObject.activeSelf;

		public UnityEvent OnShow { get; } = new UnityEvent();


		public UnityEvent OnHide { get; } = new UnityEvent();


		private void Awake()
		{
		}

		private void Start()
		{
		}

		public void Show()
		{
			((Component)this).gameObject.SetActive(true);
			UnityEvent onShow = OnShow;
			if (onShow != null)
			{
				onShow.Invoke();
			}
		}

		public void Hide()
		{
			((Component)this).gameObject.SetActive(false);
		}
	}
	[UnityScriptComponent]
	public class HotbarSettingsView : MonoBehaviour, ISettingsView
	{
		public UnityEvent<int> OnBarsChanged;

		public UnityEvent<int> OnRowsChanged;

		public UnityEvent<int> OnSlotsChanged;

		public MainSettingsMenu MainSettingsMenu;

		public HotkeyCaptureMenu HotkeyCaptureMenu;

		public ArrowInput BarAmountInput;

		public ArrowInput RowAmountInput;

		public ArrowInput SlotAmountInput;

		public Toggle ShowCooldownTimer;

		public Toggle ShowPrecisionTime;

		public Toggle HideLeftNav;

		public Toggle CombatMode;

		public Dropdown EmptySlotDropdown;

		public ArrowInput ScaleAmountInput;

		public Button SetHotkeys;

		public HotbarsContainer Hotbars;

		private bool _eventsAdded;

		private SelectableTransitions[] _selectables;

		private Selectable _lastSelected;

		public bool IsShowing => ((Component)this).gameObject.activeSelf;

		public UnityEvent OnShow { get; } = new UnityEvent();


		public UnityEvent OnHide { get; } = new UnityEvent();


		private IHotbarProfileService _hotbarService => MainSettingsMenu.PlayerMenu.ServicesProvider.GetService<IHotbarProfileService>();

		private IHotbarProfile _hotbarProfile => _hotbarService.GetProfile();

		private void Awake()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			((UnityEvent)SetHotkeys.onClick).AddListener(new UnityAction(EnableHotkeyEdits));
			_selectables = ((Component)this).GetComponentsInChildren<SelectableTransitions>();
			for (int i = 0; i < _selectables.Length; i++)
			{
				_selectables[i].OnSelected += SettingSelected;
				_selectables[i].OnDeselected += SettingDeselected;
			}
		}

		private void Start()
		{
			if (!_eventsAdded)
			{
				HookControls();
				_eventsAdded = true;
			}
		}

		public void Show()
		{
			DebugLogger.Log("HotbarSettingsViewer::Show");
			((Component)this).gameObject.SetActive(true);
			SetControls();
			((MonoBehaviour)this).StartCoroutine(SelectNextFrame((Selectable)(object)MainSettingsMenu.HotbarViewToggle));
			UnityEvent onShow = OnShow;
			if (onShow != null)
			{
				onShow.Invoke();
			}
		}

		public void Hide()
		{
			Hide(raiseEvent: true);
		}

		private void Hide(bool raiseEvent)
		{
			DebugLogger.Log("HotbarSettingsViewer::Hide");
			((Component)this).gameObject.SetActive(false);
			if (raiseEvent)
			{
				UnityEvent onHide = OnHide;
				if (onHide != null)
				{
					onHide.Invoke();
				}
			}
		}

		private void SetControls()
		{
			IActionSlotConfig config = _hotbarProfile.Hotbars.First().Slots.First().Config;
			BarAmountInput.SetAmount(_hotbarProfile.Hotbars.Count);
			RowAmountInput.SetAmount(_hotbarProfile.Rows);
			SlotAmountInput.SetAmount(_hotbarProfile.SlotsPerRow);
			ScaleAmountInput.SetAmount(_hotbarProfile.Scale);
			ShowCooldownTimer.isOn = config?.ShowCooldownTime ?? false;
			ShowPrecisionTime.isOn = config?.PreciseCooldownTime ?? false;
			HideLeftNav.isOn = _hotbarProfile?.HideLeftNav ?? false;
			CombatMode.isOn = _hotbarProfile.CombatMode;
			EmptySlotDropdown.ClearOptions();
			List<OptionData> list = ((IEnumerable<string>)Enum.GetNames(typeof(EmptySlotOptions))).Select((Func<string, OptionData>)((string name) => new OptionData(name))).ToList();
			EmptySlotDropdown.AddOptions(list);
			string selectedName = Enum.GetName(typeof(EmptySlotOptions), config?.EmptySlotOption ?? EmptySlotOptions.Image);
			EmptySlotDropdown.value = list.FindIndex((OptionData o) => o.text.Equals(selectedName, StringComparison.InvariantCultureIgnoreCase));
		}

		private void HookControls()
		{
			BarAmountInput.OnValueChanged.AddListener((UnityAction<int>)delegate(int amount)
			{
				if (_hotbarProfile.Hotbars.Count < amount)
				{
					_hotbarService.AddHotbar();
				}
				else if (_hotbarProfile.Hotbars.Count > amount)
				{
					_hotbarService.RemoveHotbar();
				}
			});
			RowAmountInput.OnValueChanged.AddListener((UnityAction<int>)delegate(int amount)
			{
				if (_hotbarProfile.Rows < amount)
				{
					_hotbarService.AddRow();
				}
				else if (_hotbarProfile.Rows > amount)
				{
					_hotbarService.RemoveRow();
				}
			});
			SlotAmountInput.OnValueChanged.AddListener((UnityAction<int>)delegate(int amount)
			{
				if (_hotbarProfile.SlotsPerRow < amount)
				{
					_hotbarService.AddSlot();
				}
				else if (_hotbarProfile.SlotsPerRow > amount)
				{
					_hotbarService.RemoveSlot();
				}
			});
			ScaleAmountInput.OnValueChanged.AddListener((UnityAction<int>)delegate(int amount)
			{
				_hotbarService.SetScale(amount);
			});
			((UnityEvent<bool>)(object)ShowCooldownTimer.onValueChanged).AddListener((UnityAction<bool>)delegate
			{
				_hotbarService.SetCooldownTimer(ShowCooldownTimer.isOn, ShowPrecisionTime.isOn);
			});
			((UnityEvent<bool>)(object)ShowPrecisionTime.onValueChanged).AddListener((UnityAction<bool>)delegate
			{
				_hotbarService.SetCooldownTimer(ShowCooldownTimer.isOn, ShowPrecisionTime.isOn);
			});
			((UnityEvent<bool>)(object)HideLeftNav.onValueChanged).AddListener((UnityAction<bool>)delegate
			{
				_hotbarService.SetHideLeftNav(HideLeftNav.isOn);
			});
			((UnityEvent<bool>)(object)CombatMode.onValueChanged).AddListener((UnityAction<bool>)delegate
			{
				_hotbarService.SetCombatMode(CombatMode.isOn);
			});
			((UnityEvent<int>)(object)EmptySlotDropdown.onValueChanged).AddListener((UnityAction<int>)delegate(int value)
			{
				_hotbarService.SetEmptySlotView((EmptySlotOptions)value);
			});
		}

		private void EnableHotkeyEdits()
		{
			HotkeyCaptureMenu.Show();
			((Component)MainSettingsMenu).gameObject.SetActive(false);
		}

		private void SettingSelected(SelectableTransitions transition)
		{
			DebugLogger.Log(((Object)transition).name + " Selected.");
			_lastSelected = transition.Selectable;
		}

		private void SettingDeselected(SelectableTransitions transition)
		{
			DebugLogger.Log(((Object)transition).name + " Deselected.");
			((MonoBehaviour)this).StartCoroutine(CheckSetSelectedSetting());
		}

		private IEnumerator CheckSetSelectedSetting()
		{
			yield return null;
			yield return (object)new WaitForEndOfFrame();
			if (!_selectables.Any((SelectableTransitions s) => s.Selected) && !MainSettingsMenu.MenuItemSelected && ((Component)this).gameObject.activeSelf && (Object)(object)_lastSelected != (Object)null)
			{
				_lastSelected.Select();
			}
		}

		private IEnumerator SelectNextFrame(Selectable selectable)
		{
			yield return null;
			yield return (object)new WaitForEndOfFrame();
			selectable.Select();
		}
	}
	[UnityScriptComponent]
	public class SettingsView : MonoBehaviour, ISettingsView
	{
		public MainSettingsMenu MainSettingsMenu;

		public Toggle ActionSlotsToggle;

		public Toggle DurabilityToggle;

		public Toggle EquipmentSetsToggle;

		public Button MoveUIButton;

		public Button ResetUIButton;

		private SelectableTransitions[] _selectables;

		private Selectable _lastSelected;

		public bool IsShowing => ((Component)this).gameObject.activeSelf;

		public UnityEvent OnShow { get; } = new UnityEvent();


		public UnityEvent OnHide { get; } = new UnityEvent();


		private IActionUIProfileService _profileService => MainSettingsMenu.PlayerMenu.ServicesProvider.GetService<IActionUIProfileService>();

		private IActionUIProfile _profile => _profileService.GetActiveProfile();

		private void Awake()
		{
			_selectables = ((Component)this).GetComponentsInChildren<SelectableTransitions>();
			for (int i = 0; i < _selectables.Length; i++)
			{
				_selectables[i].OnSelected += SettingSelected;
				_selectables[i].OnDeselected += SettingDeselected;
			}
		}

		private void Start()
		{
			if ((Object)(object)DurabilityToggle != (Object)null && (Object)(object)((Component)DurabilityToggle).gameObject != (Object)null)
			{
				((Component)DurabilityToggle).gameObject.SetActive(false);
			}
			SetControls();
			HookControls();
		}

		public void Show()
		{
			DebugLogger.Log("SettingsView::Show");
			((Component)this).gameObject.SetActive(true);
			SetControls();
			((MonoBehaviour)this).StartCoroutine(SelectNextFrame((Selectable)(object)MainSettingsMenu.SettingsViewToggle));
			UnityEvent onShow = OnShow;
			if (onShow != null)
			{
				onShow.Invoke();
			}
		}

		public void Hide()
		{
			DebugLogger.Log("SettingsView::Hide");
			((Component)this).gameObject.SetActive(false);
			UnityEvent onHide = OnHide;
			if (onHide != null)
			{
				onHide.Invoke();
			}
		}

		private void SetControls()
		{
			ActionSlotsToggle.SetIsOnWithoutNotify(_profile?.ActionSlotsEnabled ?? false);
			if ((Object)(object)DurabilityToggle != (Object)null)
			{
				DurabilityToggle.SetIsOnWithoutNotify(_profile?.DurabilityDisplayEnabled ?? false);
			}
			EquipmentSetsToggle.SetIsOnWithoutNotify(_profile?.EquipmentSetsEnabled ?? false);
		}

		private void HookControls()
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			((UnityEvent<bool>)(object)ActionSlotsToggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool isOn)
			{
				_profile.ActionSlotsEnabled = isOn;
				DebugLogger.Log($"Before ProfileService: isOn == {isOn}; ActionSlotsEnabled == {_profile.ActionSlotsEnabled}");
				IActionUIProfileService profileService = _profileService;
				DebugLogger.Log($"Before Save: isOn == {isOn}; ActionSlotsEnabled == {_profile.ActionSlotsEnabled}");
				profileService.Save();
				DebugLogger.Log($"After Save: isOn == {isOn}; ActionSlotsEnabled == {_profile.ActionSlotsEnabled}");
			});
			if ((Object)(object)DurabilityToggle != (Object)null)
			{
				((UnityEvent<bool>)(object)DurabilityToggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool isOn)
				{
					DebugLogger.Log($"DurabilityToggle changed from {!isOn} to {isOn}. Saving profile.");
					_profile.DurabilityDisplayEnabled = isOn;
					_profileService.Save();
				});
			}
			((UnityEvent<bool>)(object)EquipmentSetsToggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool isOn)
			{
				DebugLogger.Log($"EquipmentSetsToggle changed from {!isOn} to {isOn}. Saving profile.");
				_profile.EquipmentSetsEnabled = isOn;
				_profileService.Save();
			});
			((UnityEvent)MoveUIButton.onClick).AddListener(new UnityAction(ShowPositionScreen));
			((UnityEvent)ResetUIButton.onClick).AddListener(new UnityAction(ResetUIPositions));
		}

		private void ShowPositionScreen()
		{
			((Component)MainSettingsMenu).gameObject.SetActive(false);
			MainSettingsMenu.UIPositionScreen.Show();
		}

		private void ResetUIPositions()
		{
			PositionableUI[] positionableUIs = MainSettingsMenu.PlayerMenu.GetPositionableUIs();
			IPositionsProfileService service = MainSettingsMenu.PlayerMenu.ServicesProvider.GetService<IPositionsProfileService>();
			PositionsProfile profile = service.GetProfile();
			bool flag = false;
			DebugLogger.Log($"Checking {positionableUIs.Length} UI Element positons for changes.");
			PositionableUI[] array = positionableUIs;
			foreach (PositionableUI positionableUI in array)
			{
				positionableUI.ResetToOrigin();
				UIPositions uIPositions = positionableUI.GetUIPositions();
				if (positionableUI.HasMoved)
				{
					profile.AddOrReplacePosition(positionableUI.GetUIPositions());
					flag = true;
				}
			}
			if (flag)
			{
				service.Save();
			}
		}

		private void SettingSelected(SelectableTransitions transition)
		{
			DebugLogger.Log(((Object)transition).name + " Selected.");
			_lastSelected = transition.Selectable;
		}

		private void SettingDeselected(SelectableTransitions transition)
		{
			DebugLogger.Log(((Object)transition).name + " Deselected.");
			((MonoBehaviour)this).StartCoroutine(CheckSetSelectedSetting());
		}

		private IEnumerator CheckSetSelectedSetting()
		{
			yield return null;
			yield return (object)new WaitForEndOfFrame();
			if (!_selectables.Any((SelectableTransitions s) => s.Selected) && !MainSettingsMenu.MenuItemSelected && ((Component)this).gameObject.activeSelf && (Object)(object)_lastSelected != (Object)null)
			{
				_lastSelected.Select();
			}
		}

		private IEnumerator SelectNextFrame(Selectable selectable)
		{
			yield return null;
			yield return (object)new WaitForEndOfFrame();
			selectable.Select();
		}
	}
	[UnityScriptComponent]
	public class StorageSettingsView : MonoBehaviour, ISettingsView
	{
		public MainSettingsMenu MainSettingsMenu;

		public Toggle DisplayCurrencyToggle;

		public Toggle StashInventoryToggle;

		public Toggle StashInventoryAnywhereToggle;

		public Toggle MerchantStashToggle;

		public Toggle MerchantStashAnywhereToggle;

		public Toggle CraftFromStashToggle;

		public Toggle CraftFromStashAnywhereToggle;

		public Toggle PreserveFoodToggle;

		public InputField PreserveFoodAmount;

		public UnityEvent OnShow;

		public UnityEvent OnHide;

		public bool IsShowing => ((Component)this).gameObject.activeSelf;

		private void Awake()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			if (OnShow == null)
			{
				OnShow = new UnityEvent();
			}
			if (OnHide == null)
			{
				OnHide = new UnityEvent();
			}
		}

		private void Start()
		{
		}

		public void Show()
		{
			((Component)this).gameObject.SetActive(true);
			UnityEvent onShow = OnShow;
			if (onShow != null)
			{
				onShow.Invoke();
			}
		}

		public void Hide()
		{
			((Component)this).gameObject.SetActive(false);
			UnityEvent onHide = OnHide;
			if (onHide != null)
			{
				onHide.Invoke();
			}
		}
	}
	[UnityScriptComponent]
	public class SlotPanel : MonoBehaviour, IEventSystemHandler, IPointerEnterHandler, IPointerExitHandler
	{
		private Image _borderImage;

		private Image _borderHighlightImage;

		private bool _isAwake;

		public Image BorderImage => _borderImage;

		public Image ActionBorderHighlight => _borderHighlightImage;

		private void Awake()
		{
			_borderImage = ((Component)this).GetComponentsInChildren<Image>(true).First((Image i) => ((Object)i).name == "ActionBorder");
			_borderHighlightImage = ((Component)this).GetComponentsInChildren<Image>(true).First((Image i) => ((Object)i).name == "ActionBorderHighlight");
			((Behaviour)_borderHighlightImage).enabled = false;
			((Behaviour)_borderImage).enabled = true;
			_isAwake = true;
		}

		public void OnPointerEnter(PointerEventData eventData)
		{
			if (_isAwake)
			{
				((Behaviour)_borderHighlightImage).enabled = true;
				((Behaviour)_borderImage).enabled = false;
			}
		}

		public void OnPointerExit(PointerEventData eventData)
		{
			if (_isAwake)
			{
				((Behaviour)_borderHighlightImage).enabled = false;
				((Behaviour)_borderImage).enabled = true;
			}
		}
	}
	[UnityScriptComponent]
	public class UIPositionScreen : MonoBehaviour, ISettingsView
	{
		public MainSettingsMenu MainSettingsMenu;

		public Image BackPanel;

		public Text ExitScreenText;

		private bool _isInit;

		public UnityEvent OnShow { get; } = new UnityEvent();


		public UnityEvent OnHide { get; } = new UnityEvent();


		public bool IsShowing => ((Component)this).gameObject.activeSelf && _isInit;

		private void Awake()
		{
			DebugLogger.Log("UIPositionScreen::Awake");
			Hide(raiseEvent: false);
			_isInit = true;
		}

		private void Start()
		{
			DebugLogger.Log("UIPositionScreen::Start");
		}

		public void Show()
		{
			((Component)this).gameObject.SetActive(true);
			((Component)BackPanel).gameObject.SetActive(true);
			((Component)ExitScreenText).gameObject.SetActive(true);
			EnableUIPositioning();
			OnShow?.TryInvoke();
		}

		public void Hide()
		{
			Hide(raiseEvent: true);
		}

		private void Hide(bool raiseEvent)
		{
			DebugLogger.Log("UIPositionScreen::Hide");
			((Component)this).gameObject.SetActive(false);
			((Component)BackPanel).gameObject.SetActive(false);
			((Component)ExitScreenText).gameObject.SetActive(false);
			if (_isInit)
			{
				DisableAndSavePositions();
			}
			if (raiseEvent)
			{
				OnHide?.TryInvoke();
			}
		}

		private void EnableUIPositioning()
		{
			PositionableUI[] positionableUIs = MainSettingsMenu.PlayerMenu.GetPositionableUIs();
			PositionableUI[] array = positionableUIs;
			foreach (PositionableUI positionableUI in array)
			{
				positionableUI.EnableMovement();
			}
		}

		private void DisableAndSavePositions()
		{
			PositionableUI[] positionableUIs = MainSettingsMenu.PlayerMenu.GetPositionableUIs();
			IPositionsProfileService service = MainSettingsMenu.PlayerMenu.ServicesProvider.GetService<IPositionsProfileService>();
			PositionsProfile profile = service.GetProfile();
			bool flag = false;
			DebugLogger.Log($"Checking {positionableUIs.Length} UI Element positons for changes.");
			Positionabl

ModifAmorphic.Outward.ActionUI.Plugin.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Xml;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using ModifAmorphic.Outward.ActionUI.DataModels;
using ModifAmorphic.Outward.ActionUI.Extensions;
using ModifAmorphic.Outward.ActionUI.Models;
using ModifAmorphic.Outward.ActionUI.Monobehaviours;
using ModifAmorphic.Outward.ActionUI.Patches;
using ModifAmorphic.Outward.ActionUI.Plugin.Services;
using ModifAmorphic.Outward.ActionUI.Services;
using ModifAmorphic.Outward.ActionUI.Services.Injectors;
using ModifAmorphic.Outward.ActionUI.Settings;
using ModifAmorphic.Outward.Config;
using ModifAmorphic.Outward.Config.Models;
using ModifAmorphic.Outward.Coroutines;
using ModifAmorphic.Outward.Extensions;
using ModifAmorphic.Outward.GameObjectResources;
using ModifAmorphic.Outward.Logging;
using ModifAmorphic.Outward.Modules;
using ModifAmorphic.Outward.Modules.Localization;
using ModifAmorphic.Outward.Unity.ActionMenus;
using ModifAmorphic.Outward.Unity.ActionUI;
using ModifAmorphic.Outward.Unity.ActionUI.Data;
using ModifAmorphic.Outward.Unity.ActionUI.EquipmentSets;
using ModifAmorphic.Outward.Unity.ActionUI.Models.EquipmentSets;
using Newtonsoft.Json;
using Rewired;
using Rewired.Data;
using Rewired.Data.Mapping;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("ModifAmorphic.Outward.ActionUI.Plugin")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a580093fb59052c6205677075b91d046d390cb6a")]
[assembly: AssemblyProduct("ModifAmorphic.Outward.ActionUI.Plugin")]
[assembly: AssemblyTitle("ModifAmorphic.Outward.ActionUI.Plugin")]
[assembly: AssemblyVersion("1.0.0.0")]
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class ConfigurationManagerAttributes : Attribute
{
	public bool? ShowRangeAsPercent;

	public Action<ConfigEntryBase> CustomDrawer;

	public bool? Browsable;

	public string Category;

	public object DefaultValue;

	public bool? HideDefaultButton;

	public bool? HideSettingName;

	public string Description;

	public int? Order;

	public bool? ReadOnly;

	public bool? IsAdvanced;
}
namespace ModifAmorphic.Outward.ActionUI
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("ModifAmorphic.Outward.ActionUI", "Action Bar", "1.0.2")]
	public class ActionUIPlugin : BaseUnityPlugin
	{
		private static ServicesProvider _servicesProvider;

		internal static BaseUnityPlugin Instance;

		internal static ServicesProvider Services => _servicesProvider;

		internal void Awake()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			Instance = (BaseUnityPlugin)(object)this;
			ActionUISettings.Init(((BaseUnityPlugin)this).Config);
			new GlobalConfigService();
			IModifLogger val = null;
			Harmony val2 = new Harmony("ModifAmorphic.Outward.ActionUI");
			try
			{
				val = LoggerFactory.ConfigureLogger("ModifAmorphic.Outward.ActionUI", "Action Bar", (LogLevel)2);
				val.LogInfo("Patching...");
				val2.PatchAll(typeof(PauseMenuPatches));
				val2.PatchAll(typeof(SplitPlayerPatches));
				val2.PatchAll(typeof(LobbySystemPatches));
				val2.PatchAll(typeof(CharacterUIPatches));
				Startup startup = new Startup();
				val.LogInfo("Starting Action Bar 1.0.2...");
				_servicesProvider = new ServicesProvider((BaseUnityPlugin)(object)this);
				startup.Start(val2, _servicesProvider);
			}
			catch (Exception ex)
			{
				if (val != null)
				{
					val.LogException("Failed to enable ModifAmorphic.Outward.ActionUI Action Bar 1.0.2.", ex);
				}
				val2.UnpatchSelf();
				throw;
			}
		}
	}
	internal class DurabilityDisplayStartup : IStartable
	{
		private readonly Harmony _harmony;

		private readonly ServicesProvider _services;

		private readonly Func<IModifLogger> _loggerFactory;

		private readonly ModifGoService _modifGoService;

		private readonly LevelCoroutines _coroutines;

		private readonly string DurabilityModId = "ModifAmorphic.Outward.ActionUI.DurabilityDisplay";

		private IModifLogger Logger => _loggerFactory();

		public DurabilityDisplayStartup(ServicesProvider services, ModifGoService modifGoService, LevelCoroutines coroutines, Func<IModifLogger> loggerFactory)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			_services = services;
			_modifGoService = modifGoService;
			_coroutines = coroutines;
			_loggerFactory = loggerFactory;
			_harmony = new Harmony(DurabilityModId);
		}

		public void Start()
		{
			Logger.LogInfo("Starting Durability Display...");
			_harmony.PatchAll(typeof(EquipmentPatches));
			_services.AddSingleton<DurabilityDisplayService>(new DurabilityDisplayService(_services.GetService<PlayerMenuService>(), _coroutines, _loggerFactory));
		}
	}
	internal class HotbarsStartup : IStartable
	{
		private readonly Harmony _harmony;

		private readonly ServicesProvider _services;

		private readonly PlayerMenuService _playerMenuService;

		private readonly Func<IModifLogger> _loggerFactory;

		private readonly ModifGoService _modifGoService;

		private readonly LevelCoroutines _coroutines;

		private readonly string HotbarsModId = "ModifAmorphic.Outward.ActionUI.Hotbars";

		private IModifLogger Logger => _loggerFactory();

		public HotbarsStartup(ServicesProvider services, PlayerMenuService playerMenuService, ModifGoService modifGoService, LevelCoroutines coroutines, Func<IModifLogger> loggerFactory)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			_services = services;
			_playerMenuService = playerMenuService;
			_modifGoService = modifGoService;
			_coroutines = coroutines;
			_loggerFactory = loggerFactory;
			_harmony = new Harmony(HotbarsModId);
		}

		public void Start()
		{
			Logger.LogInfo("Starting Hotbars...");
			Logger.LogInfo("Patching...");
			_harmony.PatchAll(typeof(InputManager_BasePatches));
			_harmony.PatchAll(typeof(RewiredInputsPatches));
			_harmony.PatchAll(typeof(QuickSlotPanelPatches));
			_harmony.PatchAll(typeof(ControlsInputPatches));
			_harmony.PatchAll(typeof(CharacterQuickSlotManagerPatches));
			_harmony.PatchAll(typeof(SkillMenuPatches));
			_harmony.PatchAll(typeof(ItemDisplayDropGroundPatches));
			_services.AddSingleton<HotbarServicesInjector>(new HotbarServicesInjector(_services, _playerMenuService, _coroutines, _loggerFactory));
		}

		public void Stop()
		{
			_harmony.UnpatchSelf();
		}
	}
	internal class InventoryStartup : IStartable
	{
		private readonly Harmony _harmony;

		private readonly ServicesProvider _services;

		private readonly PlayerMenuService _playerMenuService;

		private readonly Func<IModifLogger> _loggerFactory;

		private readonly ModifGoService _modifGoService;

		private readonly LevelCoroutines _coroutines;

		private readonly string ModId = "ModifAmorphic.Outward.ActionUI.CharacterInventory";

		private readonly LocalizationModule _localizationsModule;

		private IModifLogger Logger => _loggerFactory();

		public InventoryStartup(ServicesProvider services, PlayerMenuService playerMenuService, ModifGoService modifGoService, LevelCoroutines coroutines, Func<IModifLogger> loggerFactory)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			_services = services;
			_playerMenuService = playerMenuService;
			_modifGoService = modifGoService;
			_coroutines = coroutines;
			_loggerFactory = loggerFactory;
			_harmony = new Harmony(ModId);
			_localizationsModule = ModifModules.GetLocalizationModule(ModId);
		}

		public void Start()
		{
			Logger.LogInfo("Starting Inventory Mods...");
			try
			{
				_localizationsModule.RegisterLocalization("Context_Item_MoveToStash", "Move to Stash");
			}
			catch (Exception ex)
			{
				Logger.LogWarning("Failed to register localizations in InventoryStartup. This is likely due to LocalizationManager not being ready yet. Proceeding with startup. Error: " + ex.Message);
			}
			_harmony.PatchAll(typeof(CharacterInventoryPatches));
			_harmony.PatchAll(typeof(EquipmentMenuPatches));
			_harmony.PatchAll(typeof(InventoryContentDisplayPatches));
			_harmony.PatchAll(typeof(ItemDisplayPatches));
			_harmony.PatchAll(typeof(ItemDisplayClickPatches));
			_harmony.PatchAll(typeof(CurrencyDisplayClickPatches));
			_harmony.PatchAll(typeof(NetworkInstantiateManagerPatches));
			_harmony.PatchAll(typeof(CharacterManagerPatches));
			_harmony.PatchAll(typeof(MenuPanelPatches));
			_harmony.PatchAll(typeof(ItemDisplayOptionPanelPatches));
			_services.AddSingleton<InventoryServicesInjector>(new InventoryServicesInjector(_services, _playerMenuService, _modifGoService, _coroutines, _loggerFactory)).AddSingleton<EquipSetPrefabService>(new EquipSetPrefabService(_services.GetService<InventoryServicesInjector>(), (ModifCoroutine)(object)_coroutines, _loggerFactory));
		}
	}
	internal interface IStartable
	{
		void Start();
	}
	internal static class ModInfo
	{
		public const string ModId = "ModifAmorphic.Outward.ActionUI";

		public const string ModName = "Action Bar";

		public const string ModVersion = "1.0.2";

		public const string MinimumConfigVersion = "1.0.0";
	}
	internal static class Starter
	{
		private static IModifLogger Logger => LoggerFactory.GetLogger("ModifAmorphic.Outward.ActionUI");

		public static bool TryStart(IStartable startable)
		{
			try
			{
				Logger.LogDebug("Starting " + startable.GetType().Name + ".");
				startable.Start();
				return true;
			}
			catch (Exception ex)
			{
				Logger.LogException("Failed to start " + startable.GetType().Name + ".", ex);
			}
			return false;
		}
	}
	internal class Startup
	{
		private ServicesProvider _services;

		private Func<IModifLogger> _loggerFactory;

		private IModifLogger Logger => _loggerFactory();

		internal void Start(Harmony harmony, ServicesProvider services)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Expected O, but got Unknown
			_services = services;
			SettingsService settingsService = new SettingsService(services.GetService<BaseUnityPlugin>(), "1.0.0");
			ConfigSettings configSettings = settingsService.ConfigureSettings();
			ActionUISettings.Init(_services.GetService<BaseUnityPlugin>().Config);
			services.AddSingleton<ConfigSettings>(configSettings).AddFactory<IModifLogger>((Func<IModifLogger>)(() => LoggerFactory.GetLogger("ModifAmorphic.Outward.ActionUI"))).AddSingleton<ModifCoroutine>(new ModifCoroutine(services.GetService<BaseUnityPlugin>(), (Func<IModifLogger>)services.GetService<IModifLogger>))
				.AddSingleton<LevelCoroutines>(new LevelCoroutines(services.GetService<BaseUnityPlugin>(), (Func<IModifLogger>)services.GetService<IModifLogger>))
				.AddSingleton<ResetActionUIsService>(new ResetActionUIsService(services, services.GetService<LevelCoroutines>(), (Func<IModifLogger>)services.GetService<IModifLogger>))
				.AddSingleton<ModifGoService>(new ModifGoService((Func<IModifLogger>)services.GetService<IModifLogger>))
				.AddSingleton<RewiredListener>(new RewiredListener(services.GetService<BaseUnityPlugin>(), services.GetService<LevelCoroutines>(), configSettings, (Func<IModifLogger>)services.GetService<IModifLogger>))
				.AddSingleton<IActionUIProfileService>((IActionUIProfileService)(object)new GlobalActionUIProfileService())
				.AddSingleton<IHotbarProfileService>((IHotbarProfileService)(object)new GlobalHotbarService())
				.AddSingleton<IPositionsProfileService>((IPositionsProfileService)(object)new GlobalPositionsService());
			_loggerFactory = services.GetServiceFactory<IModifLogger>();
			GameObject val = ConfigureAssetBundle();
			services.AddSingleton<SharedServicesInjector>(new SharedServicesInjector(services, (Func<IModifLogger>)services.GetService<IModifLogger>)).AddSingleton<PositionsService>(new PositionsService((ModifCoroutine)(object)services.GetService<LevelCoroutines>(), services.GetService<ModifGoService>(), (Func<IModifLogger>)services.GetService<IModifLogger>)).AddSingleton<PlayerMenuService>(new PlayerMenuService(services.GetService<BaseUnityPlugin>(), ((Component)val.GetComponentInChildren<PlayerActionMenus>(true)).gameObject, services.GetService<SharedServicesInjector>(), services.GetService<PositionsService>(), services.GetService<LevelCoroutines>(), services.GetService<ModifGoService>(), (Func<IModifLogger>)services.GetService<IModifLogger>))
				.AddSingleton<PositionsServicesInjector>(new PositionsServicesInjector(_services, services.GetService<PlayerMenuService>(), services.GetService<ModifGoService>(), (ModifCoroutine)(object)services.GetService<LevelCoroutines>(), (Func<IModifLogger>)services.GetService<IModifLogger>));
			services.AddSingleton<InventoryStartup>(new InventoryStartup(services, services.GetService<PlayerMenuService>(), services.GetService<ModifGoService>(), services.GetService<LevelCoroutines>(), _loggerFactory)).AddSingleton<HotbarsStartup>(new HotbarsStartup(services, services.GetService<PlayerMenuService>(), services.GetService<ModifGoService>(), services.GetService<LevelCoroutines>(), _loggerFactory));
			Starter.TryStart(services.GetService<HotbarsStartup>());
			Starter.TryStart(services.GetService<InventoryStartup>());
		}

		public GameObject ConfigureAssetBundle()
		{
			GameObject val = AttachScripts(typeof(PlayerActionMenus).Assembly);
			Logger.LogDebug("Loading asset bundle action-ui.");
			AssetBundle val2 = LoadAssetBundle(BaseUnityPluginExtensions.GetPluginDirectory(_services.GetService<BaseUnityPlugin>()), "", "action-ui");
			string[] allAssetNames = val2.GetAllAssetNames();
			string text = "";
			string[] array = allAssetNames;
			foreach (string text2 in array)
			{
				text = text + text2 + ", ";
			}
			Logger.LogDebug("Assets in Bundle: " + text);
			GameObject val3 = val2.LoadAsset<GameObject>("assets/prefabs/actionui.prefab");
			val3.SetActive(false);
			Logger.LogDebug("Loaded asset assets/prefabs/actionui.prefab.");
			Object.DontDestroyOnLoad((Object)(object)val3);
			val2.Unload(false);
			GameObject modResources = _services.GetService<ModifGoService>().GetModResources("ModifAmorphic.Outward.ActionUI", false);
			val3.transform.SetParent(modResources.transform);
			GameObject gameObject = ((Component)val3.transform.Find("PlayersServicesProvider")).gameObject;
			GameObject modResources2 = _services.GetService<ModifGoService>().GetModResources("ModifAmorphic.Outward.ActionUI", true);
			GameObject val4 = Object.Instantiate<GameObject>(gameObject);
			val4.transform.SetParent(modResources2.transform);
			((Object)val4).name = "PlayersServicesProvider";
			GameObject gameObject2 = ((Component)val3.transform.Find("ActionSprites")).gameObject;
			GameObject val5 = Object.Instantiate<GameObject>(gameObject2);
			val5.transform.SetParent(modResources2.transform);
			((Object)val5).name = "ActionSprites";
			GameObject gameObject3 = ((Component)val3.transform.Find("Prefabs")).gameObject;
			GameObject val6 = Object.Instantiate<GameObject>(gameObject3, modResources.transform);
			((Object)val6).name = "Prefabs";
			Object.Destroy((Object)(object)gameObject);
			Object.Destroy((Object)(object)gameObject2);
			Object.Destroy((Object)(object)gameObject3);
			Object.Destroy((Object)(object)val);
			return val3;
		}

		public GameObject AttachScripts(Assembly sourceAssembly)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			IEnumerable<Type> enumerable = from type in sourceAssembly.GetTypes()
				where type.GetCustomAttributes(typeof(UnityScriptComponentAttribute), inherit: true).Length != 0
				select type;
			ModifGoService service = _services.GetService<ModifGoService>();
			GameObject modResources = service.GetModResources("ModifAmorphic.Outward.ActionUI", false);
			GameObject val = new GameObject("scripts");
			val.transform.SetParent(modResources.transform);
			foreach (Type item in enumerable)
			{
				Logger.LogTrace("Attaching script " + item.FullName);
				val.AddComponent(item);
			}
			return val;
		}

		private AssetBundle LoadAssetBundle(string pluginPath, string bundleDirectory, string bundleFileName)
		{
			using FileStream fileStream = new FileStream(Path.Combine(pluginPath, Path.Combine(bundleDirectory, bundleFileName)), FileMode.Open, FileAccess.Read);
			return AssetBundle.LoadFromStream((Stream)fileStream);
		}
	}
}
namespace ModifAmorphic.Outward.ActionUI.Settings
{
	public static class ActionUISettings
	{
		public static class ActionViewer
		{
			public const string SkillsTab = "Skills";

			public const string ConsumablesTab = "Consumables";

			public const string DeployablesTab = "Deployables";

			public const string EquipmentSetsTab = "Equipment Sets";

			public const string WeaponsTab = "Weapons";

			public const string ArmorTab = "Armor";

			public const string CosmeticsTab = "Cosmetics";

			public const string EquippedTab = "Equipped";
		}

		public static readonly string PluginPath = Path.GetDirectoryName(ActionUIPlugin.Instance.Info.Location);

		public static readonly string ConfigPath = Path.GetDirectoryName(ActionUIPlugin.Instance.Config.ConfigFilePath);

		public static readonly string GlobalKeymapsPath = Path.Combine(ConfigPath, "ActionUI_Keymaps");

		public static readonly string CharacterHotbarsPath = Path.Combine(ConfigPath, "ActionUI_CharacterSlots");

		public static ConfigEntry<int> Rows;

		public static ConfigEntry<int> SlotsPerRow;

		public static ConfigEntry<int> Scale;

		public static ConfigEntry<bool> HideLeftNav;

		public static ConfigEntry<bool> CombatMode;

		public static ConfigEntry<bool> ShowCooldownTimer;

		public static ConfigEntry<bool> PreciseCooldownTime;

		public static ConfigEntry<string> EmptySlotOption;

		public static ConfigEntry<string> DisabledSlots;

		public static ConfigEntry<bool> OpenPositioningUI;

		public static ConfigEntry<bool> ResetPositions;

		public static ConfigEntry<bool> SetHotkeyMode;

		public static ConfigEntry<bool> EquipmentSetsEnabled;

		public static ConfigEntry<string> SerializedPositions;

		public static ConfigEntry<string> SerializedHotbars;

		public static void Init(ConfigFile config)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Expected O, but got Unknown
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Expected O, but got Unknown
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Expected O, but got Unknown
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Expected O, but got Unknown
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Expected O, but got Unknown
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Expected O, but got Unknown
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Expected O, but got Unknown
			//IL_0290: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Expected O, but got Unknown
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Expected O, but got Unknown
			//IL_0346: Unknown result type (might be due to invalid IL or missing references)
			//IL_0350: Expected O, but got Unknown
			//IL_03a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ab: Expected O, but got Unknown
			//IL_03ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f6: Expected O, but got Unknown
			//IL_0437: Unknown result type (might be due to invalid IL or missing references)
			//IL_0441: Expected O, but got Unknown
			EquipmentSetsEnabled = config.Bind<bool>("General", "Enable Equipment Sets", true, new ConfigDescription("Enable the Equipment Sets tab in the action viewer.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					IsAdvanced = false
				}
			}));
			Rows = config.Bind<int>("Hotbar", "Rows", 1, new ConfigDescription("Number of action bar rows.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 4), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					IsAdvanced = false
				}
			}));
			SlotsPerRow = config.Bind<int>("Hotbar", "SlotsPerRow", 11, new ConfigDescription("Number of slots per row.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 20), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					IsAdvanced = false
				}
			}));
			Scale = config.Bind<int>("Hotbar", "Scale", 100, new ConfigDescription("Scale of the action bars in percent.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(50, 200), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					IsAdvanced = false
				}
			}));
			HideLeftNav = config.Bind<bool>("Hotbar", "HideLeftNav", false, new ConfigDescription("Hide the left navigation arrows.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					IsAdvanced = false
				}
			}));
			CombatMode = config.Bind<bool>("Hotbar", "CombatMode", true, new ConfigDescription("Automatically show action bars when entering combat.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					IsAdvanced = false
				}
			}));
			ShowCooldownTimer = config.Bind<bool>("Hotbar", "ShowCooldownTimer", true, new ConfigDescription("Show numeric cooldown timer on slots.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					IsAdvanced = false
				}
			}));
			PreciseCooldownTime = config.Bind<bool>("Hotbar", "PreciseCooldownTime", false, new ConfigDescription("Show decimal precision for cooldowns.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					IsAdvanced = false
				}
			}));
			EmptySlotOption = config.Bind<string>("Hotbar", "EmptySlotDisplay", "Transparent", new ConfigDescription("How empty slots should look.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[3] { "Transparent", "Image", "Hidden" }), new object[1]
			{
				new ConfigurationManagerAttributes
				{
					IsAdvanced = false
				}
			}));
			DisabledSlots = config.Bind<string>("Hotbar", "DisabledSlots", "", new ConfigDescription("Internal list of disabled slot indices.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Browsable = false,
					IsAdvanced = true
				}
			}));
			OpenPositioningUI = config.Bind<bool>("UI Positioning", "Open Visual Editor", false, new ConfigDescription("Click to open the visual drag-and-drop editor.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					CustomDrawer = DrawPositionButton,
					HideDefaultButton = true,
					IsAdvanced = false
				}
			}));
			ResetPositions = config.Bind<bool>("UI Positioning", "Reset UI Positions", false, new ConfigDescription("Reset all UI elements to their default positions.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					CustomDrawer = DrawResetInfo,
					HideDefaultButton = true,
					IsAdvanced = false
				}
			}));
			SetHotkeyMode = config.Bind<bool>("Input", "Set Hotkey Mode", false, new ConfigDescription("Click to enter hotkey assignment mode.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					CustomDrawer = DrawHotkeyModeButton,
					HideDefaultButton = true,
					IsAdvanced = false
				}
			}));
			SerializedPositions = config.Bind<string>("Internal", "SerializedPositions", "", new ConfigDescription("JSON serialized UI positions.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Browsable = false,
					IsAdvanced = true
				}
			}));
			SerializedHotbars = config.Bind<string>("Internal", "SerializedHotbars", "", new ConfigDescription("JSON serialized hotbar configuration.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Browsable = false,
					IsAdvanced = true
				}
			}));
			Rows.SettingChanged += delegate
			{
				ApplyHotbarSettings();
			};
			SlotsPerRow.SettingChanged += delegate
			{
				ApplyHotbarSettings();
			};
			Scale.SettingChanged += delegate
			{
				ApplyHotbarSettings();
			};
			HideLeftNav.SettingChanged += delegate
			{
				ApplyHotbarSettings();
			};
			CombatMode.SettingChanged += delegate
			{
				ApplyHotbarSettings();
			};
			ShowCooldownTimer.SettingChanged += delegate
			{
				ApplyHotbarSettings();
			};
			PreciseCooldownTime.SettingChanged += delegate
			{
				ApplyHotbarSettings();
			};
			EmptySlotOption.SettingChanged += delegate
			{
				ApplyHotbarSettings();
			};
		}

		private static void CloseConfigWindow()
		{
			try
			{
				Type type = Type.GetType("ConfigurationManager.ConfigurationManager, ConfigurationManager");
				if (type == null)
				{
					return;
				}
				Object val = Object.FindObjectOfType(type);
				if (val != (Object)null)
				{
					PropertyInfo property = type.GetProperty("DisplayingWindow");
					if (property != null)
					{
						property.SetValue(val, false, null);
					}
				}
			}
			catch (Exception)
			{
			}
		}

		private static void DrawPositionButton(ConfigEntryBase entry)
		{
			if (GUILayout.Button("Open Visual Editor", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				CloseConfigWindow();
				PlayerActionMenus[] array = Object.FindObjectsOfType<PlayerActionMenus>();
				PlayerActionMenus[] array2 = array;
				foreach (PlayerActionMenus val in array2)
				{
					val.MainSettingsMenu.ShowMenu((ActionSettingsMenus)5);
				}
			}
		}

		private static void DrawResetInfo(ConfigEntryBase entry)
		{
			if (GUILayout.Button("Reset Positions", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				GlobalConfigService.Instance.PositionsProfile.Positions.Clear();
				GlobalConfigService.Instance.SavePositions();
				PlayerActionMenus[] array = Object.FindObjectsOfType<PlayerActionMenus>();
				PlayerActionMenus[] array2 = array;
				foreach (PlayerActionMenus val in array2)
				{
				}
			}
		}

		private static void DrawHotkeyModeButton(ConfigEntryBase entry)
		{
			if (!GUILayout.Button("Enter Hotkey Mode", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }))
			{
				return;
			}
			CloseConfigWindow();
			PlayerActionMenus[] array = Object.FindObjectsOfType<PlayerActionMenus>();
			PlayerActionMenus[] array2 = array;
			foreach (PlayerActionMenus val in array2)
			{
				if ((Object)(object)val.MainSettingsMenu != (Object)null && (Object)(object)val.MainSettingsMenu.HotkeyCaptureMenu != (Object)null)
				{
					val.MainSettingsMenu.HotkeyCaptureMenu.Show();
				}
			}
		}

		private static void ApplyHotbarSettings()
		{
			PlayerActionMenus[] array = Object.FindObjectsOfType<PlayerActionMenus>();
			PlayerActionMenus[] array2 = array;
			foreach (PlayerActionMenus val in array2)
			{
			}
		}
	}
	internal class ConfigSettings
	{
		private const string HotbarsSection = "Hotbars";

		private const int HotbarsTopOrder = int.MaxValue;

		private const string AdvancedSection = "zz--Advanced Settings--zz";

		private const int AdvancedTopOrder = -1000;

		public ConfigSetting<int> Hotbars { get; } = new ConfigSetting<int>
		{
			Name = "Hotbars",
			DefaultValue = 1,
			Section = "Hotbars",
			DisplayName = "Hotbars",
			Description = "Amount of hotbars.",
			Order = 2147483646,
			IsAdvanced = false
		};


		public ConfigSetting<int> ActionSlots { get; } = new ConfigSetting<int>
		{
			Name = "ActionSlots",
			DefaultValue = 8,
			Section = "Hotbars",
			DisplayName = "Hotbar Action Slots",
			Description = "The number of slots per hotbar.",
			Order = 2147483645,
			IsAdvanced = false
		};


		public ConfigSetting<LogLevel> LogLevel { get; } = new ConfigSetting<LogLevel>
		{
			Name = "LogLevel",
			DefaultValue = (LogLevel)2,
			Section = "zz--Advanced Settings--zz",
			DisplayName = "Minimum level for logging",
			Description = "The threshold for logging events to the UnityEngine.Debug logger. " + Enum.GetName(typeof(LogLevel), (object)(LogLevel)2) + " is the default.",
			Order = -1001,
			IsAdvanced = true
		};


		public ConfigSetting<string> ConfigVersion { get; } = new ConfigSetting<string>
		{
			Name = "ConfigVersion",
			DefaultValue = "1.0.2",
			Section = "zz--Advanced Settings--zz",
			DisplayName = "Created with version",
			Description = "The version of Action Bar this configuration file was created for.  **Warning - Changing this could result in resetting all config values.**",
			Order = -1002,
			IsAdvanced = true
		};

	}
	public class HotbarSettings
	{
		private static List<IHotbarSlotData> hotbarAssignments = new List<IHotbarSlotData> { (IHotbarSlotData)(object)new HotbarData
		{
			HotbarIndex = 0,
			RewiredActionId = RewiredConstants.ActionSlots.HotbarNavActions[0].id,
			RewiredActionName = RewiredConstants.ActionSlots.HotbarNavActions[0].name,
			Slots = new List<ISlotData>
			{
				(ISlotData)(object)new SlotData
				{
					SlotIndex = 0,
					Config = (IActionSlotConfig)(object)new ActionConfig
					{
						HotkeyText = "Q",
						RewiredActionName = RewiredConstants.ActionSlots.Actions[0].name,
						RewiredActionId = RewiredConstants.ActionSlots.Actions[0].id
					}
				},
				(ISlotData)(object)new SlotData
				{
					SlotIndex = 1,
					Config = (IActionSlotConfig)(object)new ActionConfig
					{
						HotkeyText = "E",
						RewiredActionName = RewiredConstants.ActionSlots.Actions[1].name,
						RewiredActionId = RewiredConstants.ActionSlots.Actions[1].id
					}
				},
				(ISlotData)(object)new SlotData
				{
					SlotIndex = 2,
					Config = (IActionSlotConfig)(object)new ActionConfig
					{
						HotkeyText = "R",
						RewiredActionName = RewiredConstants.ActionSlots.Actions[2].name,
						RewiredActionId = RewiredConstants.ActionSlots.Actions[2].id
					}
				},
				(ISlotData)(object)new SlotData
				{
					SlotIndex = 3,
					Config = (IActionSlotConfig)(object)new ActionConfig
					{
						HotkeyText = "1",
						RewiredActionName = RewiredConstants.ActionSlots.Actions[3].name,
						RewiredActionId = RewiredConstants.ActionSlots.Actions[3].id
					}
				},
				(ISlotData)(object)new SlotData
				{
					SlotIndex = 4,
					Config = (IActionSlotConfig)(object)new ActionConfig
					{
						HotkeyText = "2",
						RewiredActionName = RewiredConstants.ActionSlots.Actions[4].name,
						RewiredActionId = RewiredConstants.ActionSlots.Actions[4].id
					}
				},
				(ISlotData)(object)new SlotData
				{
					SlotIndex = 5,
					Config = (IActionSlotConfig)(object)new ActionConfig
					{
						HotkeyText = "3",
						RewiredActionName = RewiredConstants.ActionSlots.Actions[5].name,
						RewiredActionId = RewiredConstants.ActionSlots.Actions[5].id
					}
				},
				(ISlotData)(object)new SlotData
				{
					SlotIndex = 6,
					Config = (IActionSlotConfig)(object)new ActionConfig
					{
						HotkeyText = "4",
						RewiredActionName = RewiredConstants.ActionSlots.Actions[6].name,
						RewiredActionId = RewiredConstants.ActionSlots.Actions[6].id
					}
				},
				(ISlotData)(object)new SlotData
				{
					SlotIndex = 7,
					Config = (IActionSlotConfig)(object)new ActionConfig
					{
						HotkeyText = "5",
						RewiredActionName = RewiredConstants.ActionSlots.Actions[7].name,
						RewiredActionId = RewiredConstants.ActionSlots.Actions[7].id
					}
				},
				(ISlotData)(object)new SlotData
				{
					SlotIndex = 8,
					Config = (IActionSlotConfig)(object)new ActionConfig
					{
						HotkeyText = "6",
						RewiredActionName = RewiredConstants.ActionSlots.Actions[8].name,
						RewiredActionId = RewiredConstants.ActionSlots.Actions[8].id
					}
				},
				(ISlotData)(object)new SlotData
				{
					SlotIndex = 9,
					Config = (IActionSlotConfig)(object)new ActionConfig
					{
						HotkeyText = "7",
						RewiredActionName = RewiredConstants.ActionSlots.Actions[9].name,
						RewiredActionId = RewiredConstants.ActionSlots.Actions[9].id
					}
				},
				(ISlotData)(object)new SlotData
				{
					SlotIndex = 10,
					Config = (IActionSlotConfig)(object)new ActionConfig
					{
						HotkeyText = "8",
						RewiredActionName = RewiredConstants.ActionSlots.Actions[10].name,
						RewiredActionId = RewiredConstants.ActionSlots.Actions[10].id
					}
				}
			}
		} };

		internal static HotbarProfileData DefaulHotbarProfile = new HotbarProfileData
		{
			Rows = 1,
			SlotsPerRow = hotbarAssignments.First().Slots.Count,
			Hotbars = hotbarAssignments,
			HideLeftNav = false,
			CombatMode = true,
			Scale = 100,
			NextRewiredActionId = RewiredConstants.ActionSlots.NextHotbarAction.id,
			NextRewiredActionName = RewiredConstants.ActionSlots.NextHotbarAction.name,
			PrevRewiredActionId = RewiredConstants.ActionSlots.PreviousHotbarAction.id,
			PrevRewiredActionName = RewiredConstants.ActionSlots.PreviousHotbarAction.name
		};
	}
	internal class InventorySettings
	{
		public const int MaxSetItemID = -1310000000;

		public const int MinSetItemID = -1319999999;

		public const int MaxItemID = -1320000000;

		public const int MinItemID = -1329999999;

		public const string MoveToStashKey = "Context_Item_MoveToStash";

		public static readonly HashSet<AreaEnum> StashAreas = new HashSet<AreaEnum>
		{
			(AreaEnum)100,
			(AreaEnum)200,
			(AreaEnum)500,
			(AreaEnum)300,
			(AreaEnum)400,
			(AreaEnum)601
		};
	}
	internal static class RewiredConstants
	{
		public static class ActionMenus
		{
			public const int CategoryMapId = 130000;

			public static InputMapCategory CategoryMap;

			public const int ActionCategoryId = 130001;

			public static InputCategory ActionCategory;

			static ActionMenus()
			{
				CategoryMap = GetMapCategory("ActionMenus", "ActionMenus", 130000, userAssignable: true);
				ActionCategory = GetActionCategory("ActionMenus", "ActionMenus", 130001, userAssignable: true);
			}
		}

		public static class ActionSlots
		{
			public const int CategoryMapId = 131000;

			public static InputMapCategory CategoryMap;

			public const int ActionCategoryId = 131001;

			public static InputCategory ActionCategory;

			public static List<InputAction> Actions;

			public static List<InputAction> HotbarNavActions;

			public const string NameFormat = "ActionSlot_00";

			public const string NavNameFormat = "Hotbar_00";

			public static InputAction NextHotbarAction;

			public static InputAction PreviousHotbarAction;

			public static InputAction NextHotbarAxisAction;

			public static InputAction PreviousHotbarAxisAction;

			public const string SelectHotbarNameFormat = "SelectHotbar_00";

			public static readonly string DefaultKeyboardMapFile;

			public static readonly string DefaultMouseMapFile;

			public static readonly string DefaultJoystickMapFile;

			static ActionSlots()
			{
				DefaultKeyboardMapFile = Path.Combine(ActionUISettings.PluginPath, "Profiles", "Default", "Default-Keyboard-Map_ActionSlots.xml");
				DefaultMouseMapFile = Path.Combine(ActionUISettings.PluginPath, "Profiles", "Default", "Default-Mouse-Map_ActionSlots.xml");
				DefaultJoystickMapFile = string.Empty;
				CategoryMap = GetMapCategory("ActionSlots", "ActionSlots", 131000, userAssignable: true);
				ActionCategory = GetActionCategory("ActionSlots", "ActionSlots", 131001, userAssignable: true);
				Actions = GetSlotsActions("ActionSlot_00", "Action Slot ##0", (InputActionType)1, userAssignable: true, ActionCategory.id, 131500, 64);
				HotbarNavActions = GetHotbarNavActions("Hotbar_00", "Hotbar ##0", (InputActionType)1, userAssignable: true, ActionCategory.id, 131200, 64);
				NextHotbarAction = GetAction(131100, "NextHotbar", "Next Hotbar", (InputActionType)1, userAssignable: true, ActionCategory.id);
				PreviousHotbarAction = GetAction(131101, "PreviousHotbar", "Previous Hotbar", (InputActionType)1, userAssignable: true, ActionCategory.id);
				NextHotbarAxisAction = GetAction(131102, "NextHotbar+", "Next Hotbar", (InputActionType)0, userAssignable: true, ActionCategory.id);
				PreviousHotbarAxisAction = GetAction(131103, "PreviousHotbar-", "Previous Hotbar", (InputActionType)0, userAssignable: true, ActionCategory.id);
				HotbarNavActions.Add(NextHotbarAction);
				HotbarNavActions.Add(PreviousHotbarAction);
				HotbarNavActions.Add(NextHotbarAxisAction);
				HotbarNavActions.Add(PreviousHotbarAxisAction);
			}
		}

		private static InputMapCategory GetMapCategory(string name, string descriptiveName, int id, bool userAssignable)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			InputMapCategory val = new InputMapCategory();
			ReflectionExtensions.SetPrivateField<InputMapCategory, string>(val, "_name", name);
			ReflectionExtensions.SetPrivateField<InputMapCategory, string>(val, "_descriptiveName", descriptiveName);
			ReflectionExtensions.SetPrivateField<InputMapCategory, int>(val, "_id", id);
			ReflectionExtensions.SetPrivateField<InputMapCategory, bool>(val, "_userAssignable", userAssignable);
			return val;
		}

		private static InputCategory GetActionCategory(string name, string descriptiveName, int id, bool userAssignable)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			InputCategory val = new InputCategory();
			ReflectionExtensions.SetPrivateField<InputCategory, string>(val, "_name", name);
			ReflectionExtensions.SetPrivateField<InputCategory, string>(val, "_descriptiveName", descriptiveName);
			ReflectionExtensions.SetPrivateField<InputCategory, int>(val, "_id", id);
			ReflectionExtensions.SetPrivateField<InputCategory, bool>(val, "_userAssignable", userAssignable);
			return val;
		}

		private static List<InputAction> GetSlotsActions(string nameFormat, string descriptiveNameFormat, InputActionType inputActionType, bool userAssignable, int actionCategoryId, int startingId, int amount)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			List<InputAction> list = new List<InputAction>();
			for (int i = 0; i < amount; i++)
			{
				int num = i + 1;
				InputAction action = GetAction(i + startingId, num.ToString(nameFormat), num.ToString(descriptiveNameFormat), inputActionType, userAssignable, actionCategoryId);
				list.Add(action);
			}
			return list;
		}

		private static List<InputAction> GetHotbarNavActions(string nameFormat, string descriptiveNameFormat, InputActionType inputActionType, bool userAssignable, int actionCategoryId, int startingId, int amount)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			List<InputAction> list = new List<InputAction>();
			for (int i = 0; i < amount; i++)
			{
				int num = i + 1;
				InputAction action = GetAction(i + startingId, num.ToString(nameFormat), num.ToString(descriptiveNameFormat), inputActionType, userAssignable, actionCategoryId);
				list.Add(action);
			}
			return list;
		}

		public static InputAction GetAction(int id, string name, string descriptiveName, InputActionType inputActionType, bool userAssignable, int actionCategoryId)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			InputAction val = new InputAction();
			ReflectionExtensions.SetPrivateField<InputAction, int>(val, "_id", id);
			ReflectionExtensions.SetPrivateField<InputAction, string>(val, "_name", name);
			ReflectionExtensions.SetPrivateField<InputAction, string>(val, "_descriptiveName", descriptiveName);
			ReflectionExtensions.SetPrivateField<InputAction, InputActionType>(val, "_type", inputActionType);
			ReflectionExtensions.SetPrivateField<InputAction, bool>(val, "_userAssignable", userAssignable);
			ReflectionExtensions.SetPrivateField<InputAction, int>(val, "_categoryId", actionCategoryId);
			return val;
		}
	}
	internal class SettingsService
	{
		private readonly ConfigManagerService _configManagerService;

		private readonly ConfigSettingsService _configService;

		private readonly string _minConfigVersion;

		private readonly IModifLogger _logger = LoggerFactory.GetLogger("ModifAmorphic.Outward.ActionUI");

		public SettingsService(BaseUnityPlugin plugin, string minConfigVersion)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			_logger.LogTrace("SettingsService() plugin is " + (((Object)(object)plugin == (Object)null) ? "null" : "not null") + ". minConfigVersion: " + minConfigVersion);
			ConfigManagerService configManagerService = new ConfigManagerService(plugin);
			ConfigSettingsService configService = new ConfigSettingsService(plugin);
			_configManagerService = configManagerService;
			_configService = configService;
			_minConfigVersion = minConfigVersion;
		}

		public ConfigSettings ConfigureSettings()
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			ConfigSettings settings = new ConfigSettings();
			if (!MeetsMinimumVersion(_minConfigVersion))
			{
			}
			_configService.BindConfigSetting<LogLevel>(settings.LogLevel, (Action<SettingValueChangedArgs<LogLevel>>)delegate
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				LoggerFactory.ConfigureLogger("ModifAmorphic.Outward.ActionUI", "Action Bar", settings.LogLevel.Value);
			}, false, false);
			LoggerFactory.ConfigureLogger("ModifAmorphic.Outward.ActionUI", "Action Bar", settings.LogLevel.Value);
			_configService.BindConfigSetting<string>(settings.ConfigVersion, (Action<SettingValueChangedArgs<string>>)null, false, false);
			return settings;
		}

		private bool MeetsMinimumVersion(string minimumVersion)
		{
			string text = _configService.PeekSavedConfigValue<string>(new ConfigSettings().ConfigVersion);
			if (string.IsNullOrWhiteSpace(text))
			{
				return false;
			}
			if (!Version.TryParse(text, out Version result) || !Version.TryParse(minimumVersion, out Version result2))
			{
				return false;
			}
			_logger.LogDebug(string.Format("Current Config {0}? {1}. Compared: ", "MeetsMinimumVersion", result.CompareTo(result2) >= 0) + $"ConfigVersion: {result} to MinimumVersion: {result2}");
			return result.CompareTo(result2) >= 0;
		}
	}
}
namespace ModifAmorphic.Outward.ActionUI.Plugin.Services
{
	internal class RewiredListener
	{
		private readonly ConfigSettings _settings;

		private readonly Func<IModifLogger> _getLogger;

		private readonly BaseUnityPlugin _baseUnityPlugin;

		private readonly LevelCoroutines _coroutine;

		private IModifLogger Logger => _getLogger();

		public RewiredListener(BaseUnityPlugin baseUnityPlugin, LevelCoroutines coroutine, ConfigSettings settings, Func<IModifLogger> getLogger)
		{
			_baseUnityPlugin = baseUnityPlugin;
			_coroutine = coroutine;
			_settings = settings;
			_getLogger = getLogger;
			InputManager_BasePatches.BeforeInitialize += InitializeActonMenus;
		}

		private void InitializeActonMenus(InputManager_Base inputManager)
		{
			ActionCategoryMap privateField = ReflectionExtensions.GetPrivateField<UserData, ActionCategoryMap>(inputManager.userData, "actionCategoryMap");
			ReflectionExtensions.GetPrivateField<UserData, List<InputMapCategory>>(inputManager.userData, "mapCategories").Add(RewiredConstants.ActionMenus.CategoryMap);
			ReflectionExtensions.GetPrivateField<UserData, List<InputCategory>>(inputManager.userData, "actionCategories").Add(RewiredConstants.ActionMenus.ActionCategory);
			privateField.AddCategory(RewiredConstants.ActionMenus.ActionCategory.id);
			ReflectionExtensions.GetPrivateField<UserData, List<InputMapCategory>>(inputManager.userData, "mapCategories").Add(RewiredConstants.ActionSlots.CategoryMap);
			ReflectionExtensions.GetPrivateField<UserData, List<InputCategory>>(inputManager.userData, "actionCategories").Add(RewiredConstants.ActionSlots.ActionCategory);
			ReflectionExtensions.GetPrivateField<UserData, ActionCategoryMap>(inputManager.userData, "actionCategoryMap").AddCategory(RewiredConstants.ActionSlots.ActionCategory.id);
			List<InputAction> privateField2 = ReflectionExtensions.GetPrivateField<UserData, List<InputAction>>(inputManager.userData, "actions");
			foreach (InputAction action in RewiredConstants.ActionSlots.Actions)
			{
				Logger.LogDebug($"Adding action {action.name} with id {action.id}");
				ReflectionExtensions.GetPrivateField<UserData, List<InputAction>>(inputManager.userData, "actions").Add(action);
				ReflectionExtensions.GetPrivateField<UserData, ActionCategoryMap>(inputManager.userData, "actionCategoryMap").AddAction(action.categoryId, action.id);
			}
			foreach (InputAction hotbarNavAction in RewiredConstants.ActionSlots.HotbarNavActions)
			{
				Logger.LogDebug($"Adding hotbar nav action {hotbarNavAction.name} with id {hotbarNavAction.id}");
				ReflectionExtensions.GetPrivateField<UserData, List<InputAction>>(inputManager.userData, "actions").Add(hotbarNavAction);
				ReflectionExtensions.GetPrivateField<UserData, ActionCategoryMap>(inputManager.userData, "actionCategoryMap").AddAction(hotbarNavAction.categoryId, hotbarNavAction.id);
			}
		}
	}
}
namespace ModifAmorphic.Outward.ActionUI.Services
{
	internal class ControllerMapService : IDisposable
	{
		public class MouseButton
		{
			public KeyCode KeyCode { get; set; }

			public int elementIdentifierId { get; set; }

			public string DisplayName { get; set; }
		}

		private readonly Func<IModifLogger> _getLogger;

		private readonly HotkeyCaptureMenu _captureDialog;

		private readonly IHotbarProfileService _hotbarProfileService;

		private readonly IActionUIProfileService _profileService;

		private readonly HotbarService _hotbarService;

		private readonly Player _player;

		private readonly ModifCoroutine _coroutine;

		private const string KeyboardMapFile = "KeyboardMap_ActionSlots.xml";

		private const string MouseMapFile = "Mouse_ActionSlots.xml";

		private const string JoystickMapFile = "Joystick_ActionSlots.xml";

		private static Dictionary<ControllerType, string> MapFiles = new Dictionary<ControllerType, string>
		{
			{
				(ControllerType)0,
				"KeyboardMap_ActionSlots.xml"
			},
			{
				(ControllerType)1,
				"Mouse_ActionSlots.xml"
			},
			{
				(ControllerType)2,
				"Joystick_ActionSlots.xml"
			}
		};

		public static Dictionary<KeyCode, MouseButton> MouseButtons = new Dictionary<KeyCode, MouseButton>
		{
			{
				(KeyCode)0,
				new MouseButton
				{
					KeyCode = (KeyCode)0,
					elementIdentifierId = -1,
					DisplayName = string.Empty
				}
			},
			{
				(KeyCode)323,
				new MouseButton
				{
					KeyCode = (KeyCode)323,
					elementIdentifierId = 3,
					DisplayName = "LMB"
				}
			},
			{
				(KeyCode)324,
				new MouseButton
				{
					KeyCode = (KeyCode)324,
					elementIdentifierId = 4,
					DisplayName = "RMB"
				}
			},
			{
				(KeyCode)325,
				new MouseButton
				{
					KeyCode = (KeyCode)325,
					elementIdentifierId = 5,
					DisplayName = "MB 3"
				}
			},
			{
				(KeyCode)326,
				new MouseButton
				{
					KeyCode = (KeyCode)326,
					elementIdentifierId = 6,
					DisplayName = "MB 4"
				}
			},
			{
				(KeyCode)327,
				new MouseButton
				{
					KeyCode = (KeyCode)327,
					elementIdentifierId = 7,
					DisplayName = "MB 5"
				}
			},
			{
				(KeyCode)328,
				new MouseButton
				{
					KeyCode = (KeyCode)328,
					elementIdentifierId = 8,
					DisplayName = "MB 6"
				}
			}
		};

		public static Dictionary<int, MouseButton> MouseButtonElementIds = new Dictionary<int, MouseButton>
		{
			{
				2,
				new MouseButton
				{
					KeyCode = (KeyCode)325,
					elementIdentifierId = 2,
					DisplayName = "Wheel"
				}
			},
			{
				3,
				new MouseButton
				{
					KeyCode = (KeyCode)323,
					elementIdentifierId = 3,
					DisplayName = "LMB"
				}
			},
			{
				4,
				new MouseButton
				{
					KeyCode = (KeyCode)324,
					elementIdentifierId = 4,
					DisplayName = "RMB"
				}
			},
			{
				5,
				new MouseButton
				{
					KeyCode = (KeyCode)325,
					elementIdentifierId = 5,
					DisplayName = "MB 3"
				}
			},
			{
				6,
				new MouseButton
				{
					KeyCode = (KeyCode)326,
					elementIdentifierId = 6,
					DisplayName = "MB 4"
				}
			},
			{
				7,
				new MouseButton
				{
					KeyCode = (KeyCode)327,
					elementIdentifierId = 7,
					DisplayName = "MB 5"
				}
			},
			{
				8,
				new MouseButton
				{
					KeyCode = (KeyCode)328,
					elementIdentifierId = 8,
					DisplayName = "MB 6"
				}
			}
		};

		private bool disposedValue;

		private static readonly HashSet<KeyCode> MouseKeyCodes = new HashSet<KeyCode>
		{
			(KeyCode)323,
			(KeyCode)324,
			(KeyCode)325,
			(KeyCode)326,
			(KeyCode)327,
			(KeyCode)328,
			(KeyCode)329
		};

		private IModifLogger Logger => _getLogger();

		public ControllerMapService(HotkeyCaptureMenu captureDialog, IHotbarProfileService hotbarProfileService, IActionUIProfileService profileService, HotbarService hotbarService, Player player, ModifCoroutine coroutine, Func<IModifLogger> getLogger)
		{
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Expected O, but got Unknown
			_captureDialog = captureDialog;
			_hotbarService = hotbarService;
			_player = player;
			_coroutine = coroutine;
			_getLogger = getLogger;
			_hotbarProfileService = hotbarProfileService;
			_profileService = profileService;
			RewiredInputsPatches.AfterSaveAllMaps += TryRemoveActionUIMaps;
			RewiredInputsPatches.AfterExportXmlData += RewiredInputsPatches_AfterExportXmlData;
			_hotbarProfileService.OnProfileChanged += SlotAmountChanged;
			_captureDialog.OnKeysSelected += new OnKeysSelectedDelegate(CaptureDialog_OnKeysSelected);
		}

		private void RewiredInputsPatches_AfterExportXmlData(int playerId)
		{
			if (playerId == _player.id)
			{
				LoadConfigMaps(forceRefresh: true);
			}
		}

		private void TryRemoveActionUIMaps(RewiredInputs rewiredInputs)
		{
			try
			{
				if (rewiredInputs.PlayerID != _player.id)
				{
					return;
				}
				Dictionary<string, string> privateField = ReflectionExtensions.GetPrivateField<RewiredInputs, Dictionary<string, string>>(rewiredInputs, "m_mappingData");
				List<string> list = privateField.Keys.Where((string k) => UnityEngineExtensions.Contains(k, "categoryId=131000", StringComparison.InvariantCultureIgnoreCase)).ToList();
				foreach (string item in list)
				{
					try
					{
						if (privateField.Remove(item))
						{
							Logger.LogDebug("Removed ControllerMap '" + item + "'.");
						}
						else
						{
							Logger.LogWarning("Failed to remove ControllerMap '" + item + "'.");
						}
					}
					catch (Exception ex)
					{
						Logger.LogException("Exception removing ControllerMap '" + item + "'", ex);
					}
				}
			}
			catch (Exception ex2)
			{
				Logger.LogException($"Failed to remove ActionUI Controller maps for player ID {rewiredInputs.PlayerID}.", ex2);
			}
		}

		public (KeyboardMap keyboardMap, MouseMap mouseMap) LoadConfigMaps(bool forceRefresh = false)
		{
			(KeyboardMap, MouseMap) result = (GetActionSlotsMap<KeyboardMap>(forceRefresh), GetActionSlotsMap<MouseMap>(forceRefresh));
			if (forceRefresh)
			{
				_hotbarService.TryConfigureHotbars(_hotbarProfileService.GetProfile());
			}
			return result;
		}

		public void Save()
		{
			var (controllerMap, controllerMap2) = LoadConfigMaps();
			SaveControllerMap((ControllerMap)(object)controllerMap);
			SaveControllerMap((ControllerMap)(object)controllerMap2);
			ControlsInput.ExportXmlData(_player.id);
		}

		private void CaptureDialog_OnKeysSelected(int slotIndex, HotkeyCategories category, KeyGroup keyGroup)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Invalid comparison between Unknown and I4
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Invalid comparison between Unknown and I4
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Invalid comparison between Unknown and I4
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Invalid comparison between Unknown and I4
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			(KeyboardMap keyboardMap, MouseMap mouseMap) tuple = LoadConfigMaps();
			KeyboardMap item = tuple.keyboardMap;
			MouseMap item2 = tuple.mouseMap;
			List<ControllerMap> list = new List<ControllerMap>();
			string keyName = Keyboard.GetKeyName(keyGroup.KeyCode, GetModifierKeyFlags(keyGroup.Modifiers));
			Logger.LogDebug($"KeyCode {keyGroup.KeyCode} has Keyboard KeyName {keyName}.");
			ControllerType controllerType;
			if (!string.IsNullOrWhiteSpace(keyName) && !MouseKeyCodes.Contains(keyGroup.KeyCode))
			{
				controllerType = (ControllerType)0;
			}
			else
			{
				if (!MouseKeyCodes.Contains(keyGroup.KeyCode))
				{
					return;
				}
				controllerType = (ControllerType)1;
			}
			list.Add((ControllerMap)(object)item);
			list.Add((ControllerMap)(object)item2);
			if ((int)category == 1)
			{
				SetActionSlotHotkey(slotIndex, keyGroup, controllerType, list);
			}
			else if ((int)category == 4)
			{
				SetHotbarHotkey(slotIndex, keyGroup, controllerType, list);
			}
			else if ((int)category == 3 || (int)category == 2)
			{
				SetHotbarNavHotkey(category, keyGroup, controllerType, list);
			}
		}

		private void SlotAmountChanged(IHotbarProfile hotbarProfile, HotbarProfileChangeTypes changeType)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Invalid comparison between Unknown and I4
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Invalid comparison between Unknown and I4
			if (hotbarProfile.Rows != 1)
			{
				if ((int)changeType == 5)
				{
					ShiftActionSlotsForward(hotbarProfile);
				}
				else if ((int)changeType == 6)
				{
					ShiftActionSlotsBack(hotbarProfile);
				}
			}
		}

		private void ShiftActionSlotsForward(IHotbarProfile hotbarProfile)
		{
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			(KeyboardMap keyboardMap, MouseMap mouseMap) tuple = LoadConfigMaps();
			KeyboardMap item = tuple.keyboardMap;
			MouseMap item2 = tuple.mouseMap;
			List<ControllerMap> list = new List<ControllerMap>
			{
				(ControllerMap)(object)item,
				(ControllerMap)(object)item2
			};
			int index = hotbarProfile.SlotsPerRow - 1;
			int num = hotbarProfile.Rows * hotbarProfile.SlotsPerRow;
			List<IHotbarSlotData> hotbars = hotbarProfile.Hotbars;
			int num2 = hotbarProfile.Rows - 1;
			ElementAssignment assignment = default(ElementAssignment);
			for (int num3 = num2; num3 > 0; num3--)
			{
				int num4 = num3 * hotbarProfile.SlotsPerRow;
				int num5 = (num3 + 1) * hotbarProfile.SlotsPerRow - 1;
				for (int num6 = num5; num6 >= num4; num6--)
				{
					ActionConfig actionConfig = hotbars[0].Slots[num6].Config as ActionConfig;
					ControllerType val = (ControllerType)0;
					int previousActionId = ((ActionConfig)(object)hotbars[0].Slots[num6].Config).RewiredActionId - num3;
					ActionElementMap val2 = ((IEnumerable<ActionElementMap>)((ControllerMap)item).ButtonMaps).FirstOrDefault((Func<ActionElementMap, bool>)((ActionElementMap m) => m.actionId == previousActionId));
					ControllerMap map = (ControllerMap)(object)item;
					if (val2 == null || num6 == num5)
					{
						((ElementAssignment)(ref assignment))..ctor(val, (ControllerElementType)1, -1, (AxisRange)1, (KeyCode)0, (ModifierKeyFlags)0, actionConfig.RewiredActionId, (Pole)0, false);
					}
					else
					{
						((ElementAssignment)(ref assignment))..ctor(val, (ControllerElementType)1, val2.elementIdentifierId, (AxisRange)1, val2.keyCode, val2.modifierKeyFlags, actionConfig.RewiredActionId, (Pole)0, false);
					}
					ConfigureButtonMapping(assignment, val, map, out var hotkeyText);
					actionConfig.HotkeyText = hotkeyText;
				}
			}
			ActionConfig actionConfig2 = hotbars[0].Slots[index].Config as ActionConfig;
			ConfigureButtonMapping(new ElementAssignment((KeyCode)0, (ModifierKeyFlags)0, actionConfig2.RewiredActionId, (Pole)0, -1), (ControllerType)0, (ControllerMap)(object)item, out var hotkeyText2);
			ConfigureButtonMapping(new ElementAssignment((KeyCode)0, (ModifierKeyFlags)0, actionConfig2.RewiredActionId, (Pole)0, -1), (ControllerType)0, (ControllerMap)(object)item2, out hotkeyText2);
			actionConfig2.HotkeyText = string.Empty;
			for (int i = 1; i < hotbars.Count; i++)
			{
				for (int j = 0; j < hotbars[i].Slots.Count; j++)
				{
					hotbars[i].Slots[j].Config.HotkeyText = hotbars[0].Slots[j].Config.HotkeyText;
				}
			}
			SaveControllerMap((ControllerMap)(object)item);
			SaveControllerMap((ControllerMap)(object)item2);
		}

		private void ShiftActionSlotsBack(IHotbarProfile hotbarProfile)
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			(KeyboardMap keyboardMap, MouseMap mouseMap) tuple = LoadConfigMaps();
			KeyboardMap item = tuple.keyboardMap;
			MouseMap item2 = tuple.mouseMap;
			List<ControllerMap> list = new List<ControllerMap>
			{
				(ControllerMap)(object)item,
				(ControllerMap)(object)item2
			};
			List<IHotbarSlotData> hotbars = hotbarProfile.Hotbars;
			ElementAssignment assignment = default(ElementAssignment);
			for (int i = 1; i < hotbarProfile.Rows; i++)
			{
				int num = i * hotbarProfile.SlotsPerRow;
				int num2 = (i + 1) * hotbarProfile.SlotsPerRow - 1;
				for (int j = num; j <= num2; j++)
				{
					ActionConfig actionConfig = hotbars[0].Slots[j].Config as ActionConfig;
					int nextActionId = ((ActionConfig)(object)hotbars[0].Slots[j].Config).RewiredActionId + i;
					ControllerType val = (ControllerType)0;
					ActionElementMap val2 = ((IEnumerable<ActionElementMap>)((ControllerMap)item).ButtonMaps).FirstOrDefault((Func<ActionElementMap, bool>)((ActionElementMap m) => m.actionId == nextActionId));
					ControllerMap map = (ControllerMap)(object)item;
					if (val2 == null)
					{
						val2 = ((IEnumerable<ActionElementMap>)((ControllerMap)item2).ButtonMaps).FirstOrDefault((Func<ActionElementMap, bool>)((ActionElementMap m) => m.actionId == nextActionId));
						val = (ControllerType)1;
						map = (ControllerMap)(object)item2;
					}
					if (val2 == null)
					{
						((ElementAssignment)(ref assignment))..ctor(val, (ControllerElementType)1, -1, (AxisRange)1, (KeyCode)0, (ModifierKeyFlags)0, actionConfig.RewiredActionId, (Pole)0, false);
					}
					else
					{
						((ElementAssignment)(ref assignment))..ctor(val, (ControllerElementType)1, val2.elementIdentifierId, (AxisRange)1, val2.keyCode, val2.modifierKeyFlags, actionConfig.RewiredActionId, (Pole)0, false);
					}
					ConfigureButtonMapping(assignment, val, map, out var hotkeyText);
					actionConfig.HotkeyText = hotkeyText;
				}
			}
			for (int k = 1; k < hotbars.Count; k++)
			{
				for (int l = 0; l < hotbars[k].Slots.Count; l++)
				{
					hotbars[k].Slots[l].Config.HotkeyText = hotbars[0].Slots[l].Config.HotkeyText;
				}
			}
			SaveControllerMap((ControllerMap)(object)item);
			SaveControllerMap((ControllerMap)(object)item2);
		}

		private void SetActionSlotHotkey(int slotIndex, KeyGroup keyGroup, ControllerType controllerType, List<ControllerMap> maps)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			Logger.LogDebug($"Setting ActionSlot Hotkey for Slot Index {slotIndex} to KeyCode {keyGroup.KeyCode}.");
			IHotbarProfile profile = _hotbarProfileService.GetProfile();
			List<IHotbarSlotData> hotbars = profile.Hotbars;
			ActionConfig actionConfig = (ActionConfig)(object)hotbars[0].Slots[slotIndex].Config;
			ConfigureButtonMapping(actionConfig.RewiredActionId, keyGroup, controllerType, maps, out var hotkeyText);
			for (int i = 0; i < hotbars.Count; i++)
			{
				hotbars[i].Slots[slotIndex].Config.HotkeyText = hotkeyText;
				Logger.LogDebug($"Setting Hotkey to '{hotkeyText}' for hotbar {i}, slot {slotIndex}.");
			}
			_hotbarProfileService.Save();
			_hotbarService.TryConfigureHotbars(profile);
		}

		private void SetHotbarHotkey(int id, KeyGroup keyGroup, ControllerType controllerType, IEnumerable<ControllerMap> maps)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			Logger.LogDebug($"Setting Hotbar Hotkey for Bar Index {id}.");
			IHotbarProfile profile = _hotbarProfileService.GetProfile();
			HotbarData hotbarData = (HotbarData)(object)profile.Hotbars[id];
			ConfigureButtonMapping(hotbarData.RewiredActionId, keyGroup, controllerType, maps, out var hotkeyText);
			hotbarData.HotbarHotkey = hotkeyText;
			_hotbarProfileService.Save();
			_hotbarService.TryConfigureHotbars(profile);
		}

		private void SetHotbarNavHotkey(HotkeyCategories category, KeyGroup keyGroup, ControllerType controllerType, IEnumerable<ControllerMap> maps)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Invalid comparison between Unknown and I4
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Invalid comparison between Unknown and I4
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Invalid comparison between Unknown and I4
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Invalid comparison between Unknown and I4
			HotbarProfileData hotbarProfileData = (HotbarProfileData)(object)_hotbarProfileService.GetProfile();
			int rewiredActionId = (((int)category == 3) ? hotbarProfileData.NextRewiredActionId : hotbarProfileData.PrevRewiredActionId);
			if ((int)keyGroup.KeyCode == 325 && (int)keyGroup.AxisDirection > 0)
			{
				rewiredActionId = (((int)category == 3) ? hotbarProfileData.NextRewiredAxisActionId : hotbarProfileData.PrevRewiredAxisActionId);
			}
			ConfigureButtonMapping(rewiredActionId, keyGroup, controllerType, maps, out var hotkeyText);
			if ((int)category == 3)
			{
				hotbarProfileData.NextHotkey = hotkeyText;
				Logger.LogDebug("Setting NextHotkey text to " + hotkeyText + ".");
			}
			else
			{
				Logger.LogDebug("Setting PrevHotkey text to " + hotkeyText + ".");
				hotbarProfileData.PrevHotkey = hotkeyText;
			}
			_hotbarProfileService.Save();
			_hotbarService.TryConfigureHotbars((IHotbarProfile)(object)hotbarProfileData);
		}

		private void ConfigureButtonMapping(int rewiredActionId, KeyGroup keyGroup, ControllerType controllerType, IEnumerable<ControllerMap> maps, out string hotkeyText)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Invalid comparison between Unknown and I4
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Invalid comparison between Unknown and I4
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Invalid comparison between Unknown and I4
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Invalid comparison between Unknown and I4
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Invalid comparison between Unknown and I4
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Invalid comparison between Unknown and I4
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			hotkeyText = string.Empty;
			ElementAssignment assignment = default(ElementAssignment);
			foreach (ControllerMap map in maps)
			{
				int num = -1;
				AxisRange val = (AxisRange)(((int)keyGroup.AxisDirection != 2) ? 1 : 2);
				Pole val2 = (Pole)((int)keyGroup.AxisDirection == 2);
				if (map.controllerType == controllerType)
				{
					if ((int)controllerType == 1)
					{
						num = (((int)keyGroup.KeyCode != 325 || (int)keyGroup.AxisDirection <= 0) ? MouseButtons[keyGroup.KeyCode].elementIdentifierId : 2);
					}
					Logger.LogDebug($"Configuring Button Mapping for ControllerType {map.controllerType} and actionId {rewiredActionId}. Setting elementIdentifierId to {num}.  Keycode is {keyGroup.KeyCode}");
					if ((int)keyGroup.AxisDirection == 0)
					{
						((ElementAssignment)(ref assignment))..ctor(map.controllerType, (ControllerElementType)1, num, (AxisRange)1, keyGroup.KeyCode, GetModifierKeyFlags(keyGroup.Modifiers), rewiredActionId, (Pole)0, false);
					}
					else
					{
						((ElementAssignment)(ref assignment))..ctor(map.controllerType, (ControllerElementType)0, num, val, keyGroup.KeyCode, GetModifierKeyFlags(keyGroup.Modifiers), rewiredActionId, val2, false);
					}
				}
				else
				{
					Logger.LogDebug($"Configuring Removal Button Mapping for ControllerType {map.controllerType} and actionId {rewiredActionId}.");
					((ElementAssignment)(ref assignment))..ctor(map.controllerType, (ControllerElementType)1, num, (AxisRange)1, (KeyCode)0, (ModifierKeyFlags)0, rewiredActionId, (Pole)0, false);
				}
				ConfigureButtonMapping(assignment, controllerType, map, out var hotkeyText2);
				if (!string.IsNullOrWhiteSpace(hotkeyText2))
				{
					hotkeyText = hotkeyText2;
				}
				SaveControllerMap(map);
			}
		}

		private void ConfigureButtonMapping(ElementAssignment assignment, ControllerType controllerType, ControllerMap map, out string hotkeyText)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Invalid comparison between Unknown and I4
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Invalid comparison between Unknown and I4
			//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Invalid comparison between Unknown and I4
			//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Invalid comparison between Unknown and I4
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Invalid comparison between Unknown and I4
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Invalid comparison between Unknown and I4
			hotkeyText = string.Empty;
			List<ActionElementMap> maps = map.AllMaps.Where((ActionElementMap m) => m.actionId == assignment.actionId).ToList();
			AddHotbarNavMaps(assignment, map, ref maps);
			if (maps.Any())
			{
				for (int i = 0; i < maps.Count; i++)
				{
					if (map.DeleteElementMap(maps[i].id))
					{
						Logger.LogDebug($"Deleted existing map {maps[i].id} for rewiredId {assignment.actionId}.");
					}
				}
			}
			RemoveExistingAssignments(assignment, map);
			if (map.controllerType != controllerType)
			{
				return;
			}
			if ((int)assignment.keyboardKey != 0 || ((int)map.controllerType == 1 && MouseButtonElementIds.TryGetValue(assignment.elementIdentifierId, out var value) && (int)value.KeyCode > 0))
			{
				bool flag = map.ReplaceOrCreateElementMap(assignment);
				Logger.LogDebug($"Attempted replace or create element map {assignment.elementMapId} to use keyboardKey {assignment.keyboardKey} in {map.controllerType} ControllerMap {map.id}.  Result was {flag}");
			}
			ActionElementMap? obj = ((IEnumerable<ActionElementMap>)map.ButtonMaps).FirstOrDefault((Func<ActionElementMap, bool>)((ActionElementMap m) => m.actionId == assignment.actionId));
			hotkeyText = ((obj != null) ? obj.elementIdentifierName : null);
			if ((int)map.controllerType != 1 || !MouseButtonElementIds.TryGetValue(assignment.elementIdentifierId, out var value2))
			{
				return;
			}
			hotkeyText = value2.DisplayName;
			if ((int)value2.KeyCode == 325)
			{
				if ((int)assignment.axisRange == 1)
				{
					hotkeyText += "+";
				}
				else if ((int)assignment.axisRange == 2)
				{
					hotkeyText += "-";
				}
			}
		}

		private void RemoveExistingAssignments(ElementAssignment assignment, ControllerMap map)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			ElementAssignmentConflictCheck val = CreateConflictCheck(map, assignment);
			int num = map.RemoveElementAssignmentConflicts(val);
			Logger.LogDebug($"Removed {num} conflicts for key {assignment.keyboardKey} and modifiers {assignment.modifierKeyFlags}.");
		}

		private ElementAssignmentConflictCheck CreateConflictCheck(ControllerMap map, ElementAssignment assignment)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			ElementAssignmentConflictCheck result = ((ElementAssignment)(ref assignment)).ToElementAssignmentConflictCheck();
			((ElementAssignmentConflictCheck)(ref result)).playerId = map.id;
			((ElementAssignmentConflictCheck)(ref result)).controllerType = map.controllerType;
			((ElementAssignmentConflictCheck)(ref result)).controllerId = map.controllerId;
			((ElementAssignmentConflictCheck)(ref result)).controllerMapId = map.id;
			((ElementAssignmentConflictCheck)(ref result)).controllerMapCategoryId = map.categoryId;
			return result;
		}

		private void AddHotbarNavMaps(ElementAssignment assignment, ControllerMap map, ref List<ActionElementMap> maps)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			if (assignment.actionId == RewiredConstants.ActionSlots.NextHotbarAction.id)
			{
				ActionElementMap val = ((IEnumerable<ActionElementMap>)map.AllMaps).FirstOrDefault((Func<ActionElementMap, bool>)((ActionElementMap m) => m.actionId == RewiredConstants.ActionSlots.NextHotbarAxisAction.id));
				if (val != null)
				{
					maps.Add(val);
				}
			}
			if (assignment.actionId == RewiredConstants.ActionSlots.PreviousHotbarAction.id)
			{
				ActionElementMap val2 = ((IEnumerable<ActionElementMap>)map.AllMaps).FirstOrDefault((Func<ActionElementMap, bool>)((ActionElementMap m) => m.actionId == RewiredConstants.ActionSlots.PreviousHotbarAxisAction.id));
				if (val2 != null)
				{
					maps.Add(val2);
				}
			}
			if (assignment.actionId == RewiredConstants.ActionSlots.NextHotbarAxisAction.id)
			{
				ActionElementMap val3 = ((IEnumerable<ActionElementMap>)map.AllMaps).FirstOrDefault((Func<ActionElementMap, bool>)((ActionElementMap m) => m.actionId == RewiredConstants.ActionSlots.NextHotbarAction.id));
				if (val3 != null)
				{
					maps.Add(val3);
				}
			}
			if (assignment.actionId == RewiredConstants.ActionSlots.PreviousHotbarAxisAction.id)
			{
				ActionElementMap val4 = ((IEnumerable<ActionElementMap>)map.AllMaps).FirstOrDefault((Func<ActionElementMap, bool>)((ActionElementMap m) => m.actionId == RewiredConstants.ActionSlots.PreviousHotbarAction.id));
				if (val4 != null)
				{
					maps.Add(val4);
				}
			}
		}

		private void SaveControllerMap(ControllerMap controllerMap)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			string text = Path.Combine(GetProfileFolder(), MapFiles[controllerMap.controllerType]);
			Logger.LogInfo($"Saving Controller Map {((controllerMap != null) ? new ControllerType?(controllerMap.controllerType) : null)} to '{text}'.");
			string xml = controllerMap.ToXmlString();
			XmlDocument xmlDocument = new XmlDocument();
			xmlDocument.LoadXml(xml);
			using XmlTextWriter xmlTextWriter = new XmlTextWriter(text, Encoding.UTF8);
			xmlTextWriter.Formatting = Formatting.Indented;
			xmlTextWriter.Indentation = 4;
			xmlDocument.Save(xmlTextWriter);
			xmlTextWriter.Close();
		}

		private T GetActionSlotsMap<T>(bool forceRefresh) where T : ControllerMap
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Invalid comparison between Unknown and I4
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			ControllerType val = (ControllerType)20;
			if (typeof(KeyboardMap).IsAssignableFrom(typeof(T)))
			{
				val = (ControllerType)0;
			}
			else if (typeof(MouseMap).IsAssignableFrom(typeof(T)))
			{
				val = (ControllerType)1;
			}
			else if (typeof(JoystickMap).IsAssignableFrom(typeof(T)))
			{
				val = (ControllerType)2;
			}
			Logger.LogDebug($"ActionSlots using {val} ControllerMap for player {_player.id}");
			if ((int)val == 20)
			{
				return default(T);
			}
			T map = _player.controllers.maps.GetMap<T>(0, 131000, 0);
			if (map != null && !forceRefresh)
			{
				Logger.LogDebug($"ActionSlots {val} ControllerMap found loaded for player {_player.id}");
				return map;
			}
			string keyMapFileXml = GetKeyMapFileXml(val);
			T val2 = (T)(object)ControllerMap.CreateFromXml(val, keyMapFileXml);
			if (map != null)
			{
				Logger.LogDebug($"Replacing ActionSlots {val} ControllerMap found loaded for player {_player.id}");
				_player.controllers.maps.RemoveMap<T>(0, ((ControllerMap)val2).id);
			}
			_player.controllers.maps.AddMap<T>(0, (ControllerMap)(object)val2);
			return val2;
		}

		private string GetKeyMapFileXml(ControllerType controllerType)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Invalid comparison between Unknown and I4
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Invalid comparison between Unknown and I4
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			HotbarProfileData hotbarProfileData = (HotbarProfileData)(object)_hotbarProfileService.GetProfile();
			string text;
			string text2;
			if ((int)controllerType == 0)
			{
				text = RewiredConstants.ActionSlots.DefaultKeyboardMapFile;
				text2 = Path.Combine(ActionUISettings.PluginPath, "Default-Keyboard-Map_ActionSlots.xml");
			}
			else if ((int)controllerType == 1)
			{
				text = RewiredConstants.ActionSlots.DefaultMouseMapFile;
				text2 = Path.Combine(ActionUISettings.PluginPath, "Default-Mouse-Map_ActionSlots.xml");
			}
			else
			{
				if ((int)controllerType != 2)
				{
					return string.Empty;
				}
				text = RewiredConstants.ActionSlots.DefaultJoystickMapFile;
				text2 = string.Empty;
			}
			string text3 = text;
			if (!File.Exists(text3) && !string.IsNullOrEmpty(text2) && File.Exists(text2))
			{
				Logger.LogDebug("Default keymap not found at '" + text + "', using fallback at '" + text2 + "'.");
				text3 = text2;
			}
			string text4 = text3;
			if (hotbarProfileData != null)
			{
				text4 = Path.Combine(GetProfileFolder(), MapFiles[controllerType]);
				if (!File.Exists(text4))
				{
					string directoryName = Path.GetDirectoryName(text4);
					if (!Directory.Exists(directoryName))
					{
						Directory.CreateDirectory(directoryName);
					}
					if (!File.Exists(text3))
					{
						Logger.LogWarning("No default keymap file found. Checked: '" + text + "' and '" + text2 + "'. Cannot create profile keymap.");
						return string.Empty;
					}
					File.Copy(text3, text4);
					Logger.LogDebug("Copied default keymap from '" + text3 + "' to '" + text4 + "'.");
				}
			}
			Logger.LogDebug($"Loading ActionSlots {controllerType} ControllerMap for player {_player.id} at location '{text4}'.");
			return File.ReadAllText(text4);
		}

		private string GetProfileFolder()
		{
			if (!Directory.Exists(ActionUISettings.GlobalKeymapsPath))
			{
				Directory.CreateDirectory(ActionUISettings.GlobalKeymapsPath);
			}
			return ActionUISettings.GlobalKeymapsPath;
		}

		private ModifierKeyFlags GetModifierKeyFlags(IEnumerable<KeyCode> modifiers)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			ModifierKeyFlags val = (ModifierKeyFlags)0;
			if (modifiers.Contains((KeyCode)307) || modifiers.Contains((KeyCode)308))
			{
				val = (ModifierKeyFlags)(val | 0xC);
			}
			if (modifiers.Contains((KeyCode)305) || modifiers.Contains((KeyCode)306))
			{
				val = (ModifierKeyFlags)(val | 3);
			}
			if (modifiers.Contains((KeyCode)303) || modifiers.Contains((KeyCode)304))
			{
				val = (ModifierKeyFlags)(val | 0x30);
			}
			return val;
		}

		protected virtual void Dispose(bool disposing)
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Expected O, but got Unknown
			if (disposedValue)
			{
				return;
			}
			if (disposing)
			{
				RewiredInputsPatches.AfterSaveAllMaps -= TryRemoveActionUIMaps;
				RewiredInputsPatches.AfterExportXmlData -= RewiredInputsPatches_AfterExportXmlData;
				if (_hotbarProfileService != null)
				{
					_hotbarProfileService.OnProfileChanged -= SlotAmountChanged;
				}
				if ((Object)(object)_captureDialog != (Object)null)
				{
					_captureDialog.OnKeysSelected -= new OnKeysSelectedDelegate(CaptureDialog_OnKeysSelected);
				}
			}
			disposedValue = true;
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}
	}
	internal class HotbarKeyListener : IHotbarNavActions
	{
		private readonly Player _player;

		public HotbarKeyListener(Player player)
		{
			_player = player;
		}

		public bool IsNextRequested()
		{
			return _player.GetButtonDown(RewiredConstants.ActionSlots.NextHotbarAction.id) || !Mathf.Approximately(_player.GetAxis(RewiredConstants.ActionSlots.NextHotbarAxisAction.id), 0f);
		}

		public bool IsPreviousRequested()
		{
			return _player.GetButtonDown(RewiredConstants.ActionSlots.PreviousHotbarAction.id) || !Mathf.Approximately(_player.GetAxis(RewiredConstants.ActionSlots.PreviousHotbarAxisAction.id), 0f);
		}

		public bool IsHotbarRequested(out int hotbarIndex)
		{
			hotbarIndex = -1;
			if (!_player.GetAnyButtonDown())
			{
				return false;
			}
			for (int i = 0; i < RewiredConstants.ActionSlots.HotbarNavActions.Count; i++)
			{
				if (_player.GetButtonDown(RewiredConstants.ActionSlots.HotbarNavActions[i].id))
				{
					hotbarIndex = i;
					return true;
				}
			}
			return false;
		}
	}
	internal class HotbarService : IDisposable
	{
		private readonly Func<IModifLogger> _getLogger;

		private readonly HotbarsContainer _hotbars;

		private readonly Player _player;

		private readonly Character _character;

		private readonly CharacterUI _characterUI;

		private readonly IHotbarProfileService _hotbarProfileService;

		private readonly IActionUIProfileService _profileService;

		private readonly SlotDataService _slotData;

		private readonly LevelCoroutines _levelCoroutines;

		private bool _saveDisabled;

		private bool _isProfileInit;

		private bool _isStarted = false;

		private bool disposedValue;

		private bool _isConfiguring = false;

		private IModifLogger Logger => _getLogger();

		public Guid InstanceID { get; } = Guid.NewGuid();


		public HotbarService(HotbarsContainer hotbarsContainer, Player player, Character character, IHotbarProfileService hotbarProfileService, IActionUIProfileService profileService, SlotDataService slotData, LevelCoroutines levelCoroutines, Func<IModifLogger> getLogger)
		{
			if ((Object)(object)hotbarsContainer == (Object)null)
			{
				throw new ArgumentNullException("hotbarsContainer");
			}
			if ((Object)(object)character == (Object)null)
			{
				throw new ArgumentNullException("character");
			}
			if (hotbarProfileService == null)
			{
				throw new ArgumentNullException("hotbarProfileService");
			}
			if (profileService == null)
			{
				throw new ArgumentNullException("profileService");
			}
			if (slotData == null)
			{
				throw new ArgumentNullException("slotData");
			}
			_hotbars = hotbarsContainer;
			_player = player;
			_character = character;
			_characterUI = character.CharacterUI;
			_hotbarProfileService = hotbarProfileService;
			_profileService = profileService;
			_slotData = slotData;
			_levelCoroutines = levelCoroutines;
			_getLogger = getLogger;
			QuickSlotPanelPatches.StartInitAfter += DisableKeyboardQuickslots;
			SkillMenuPatches.AfterOnSectionSelected += SetSkillsMovable;
			ItemDisplayDropGroundPatches.TryGetIsDropValids.Add(_player.id, TryGetIsDropValid);
			_hotbars.OnAwake += StartNextFrame;
			if (_hotbars.IsAwake)
			{
				StartNextFrame();
			}
		}

		private void StartNextFrame()
		{
			try
			{
				((ModifCoroutine)_levelCoroutines).DoNextFrame((Action)delegate
				{
					Start();
				});
			}
			catch (Exception ex)
			{
				Logger.LogException("Failed to start HotbarService coroutine Start.", ex);
			}
		}

		public void Start()
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				_isStarted = true;
				_saveDisabled = true;
				SwapCanvasGroup();
				IHotbarProfile orCreateActiveProfile = GetOrCreateActiveProfile();
				if (_hotbarProfileService is GlobalHotbarService globalHotbarService)
				{
					globalHotbarService.LoadCharacterSlots(UID.op_Implicit(_character.UID));
				}
				TryConfigureHotbars(orCreateActiveProfile, (HotbarProfileChangeTypes)0);
				_hotbars.ClearChanges();
				_hotbarProfileService.OnProfileChanged += TryConfigureHotbars;
				_hotbars.OnHasChanges.AddListener(new UnityAction(Save));
				CharacterUIPatches.AfterRefreshHUDVisibility += ShowHideHotbars;
				AssignSlotActions();
				ShowHideHotbars(_characterUI);
			}
			catch (Exception ex)
			{
				Logger.LogException("Failed to start HotbarService.", ex);
			}
		}

		private void ShowHideHotbars(CharacterUI characterui)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (!(characterui.TargetCharacter.UID != _character.UID))
			{
				int num = UnityEngineExtensions.ToInt(OptionManager.Instance.GetHudVisibility(_character.OwnerPlayerSys.PlayerID));
				((Component)_hotbars.ActionBarsCanvas).GetComponent<CanvasGroup>().alpha = num;
			}
		}

		private void SetSkillsMovable(ItemListDisplay itemListDisplay)
		{
			IActionUIProfile activeProfile = _profileService.GetActiveProfile();
			if (activeProfile == null || activeProfile.ActionSlotsEnabled)
			{
				ItemDisplay[] componentsInChildren = ((Component)itemListDisplay).GetComponentsInChildren<ItemDisplay>();
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					componentsInChildren[i].Movable = true;
				}
			}
		}

		private bool TryGetIsDropValid(ItemDisplay draggedDisplay, Character character, out bool result)
		{
			result = false;
			if (!((Object)(object)((draggedDisplay != null) ? draggedDisplay.RefItem : null) == (Object)null))
			{
				Item refItem = draggedDisplay.RefItem;
				Skill val = (Skill)(object)((refItem is Skill) ? refItem : null);
				if (val != null)
				{
					Logger.LogDebug("TryGetIsDropValid:: Blocking drop of skill " + ((Object)val).name + " to DropPanel.");
					return true;
				}
			}
			return false;
		}

		public void TryConfigureHotbars(IHotbarProfile profile)
		{
			try
			{
				if (!_hotbars.IsAwake || !_isStarted)
				{
					return;
				}
				Character character = _character;
				if ((Object)(object)((character != null) ? character.Inventory : null) == (Object)null)
				{
					return;
				}
				_isConfiguring = true;
				_saveDisabled = true;
				SetProfileHotkeys(profile);
				_hotbars.Controller.ConfigureHotbars(profile);
				ActionSlot[][] hotbars = _hotbars.Hotbars;
				foreach (ActionSlot[] array in hotbars)
				{
					if (array == null)
					{
						continue;
					}
					ActionSlot[] array2 = array;
					foreach (ActionSlot val in array2)
					{
						if ((Object)(object)val != (Object)null && (Object)(object)val.ActionButton != (Object)null)
						{
							UnityEngineExtensions.GetOrAddComponent<ActionSlotDropper>(((Component)val.ActionButton).gameObject).SetLogger(_getLogger);
						}
					}
				}
				if (profile.HideLeftNav)
				{
					_hotbars.LeftHotbarNav.Hide();
				}
				else
				{
					_hotbars.LeftHotbarNav.Show();
				}
				if (_isProfileInit)
				{
					AssignSlotActions(profile);
				}
				ScaleHotbars(profile.Scale);
			}
			catch (Exception ex)
			{
				Logger.LogException("Failed to configure Hotbars.", ex);
			}
			finally
			{
				_isConfiguring = false;
				_saveDisabled = false;
			}
		}

		private void TryConfigureHotbars(IHotbarProfile profile, HotbarProfileChangeTypes changeType)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Invalid comparison between Unknown and I4
			try
			{
				if ((int)changeType == 11)
				{
					ScaleHotbars(profile.Scale);
				}
				else
				{
					TryConfigureHotbars(profile);
				}
			}
			catch (Exception ex)
			{
				Logger.LogException("Failed to configure Hotbars.", ex);
			}
		}

		private void Save()
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!_isConfiguring && _hotbars.HasChanges && !_saveDisabled)
				{
					IHotbarProfile orCreateActiveProfile = GetOrCreateActiveProfile();
					Logger.LogDebug(string.Format("{0}_{1}: Hotbar changes detected. Saving.", "HotbarService", InstanceID));
					_hotbarProfileService.Update(_hotbars);
					if (_hotbarProfileService is GlobalHotbarService globalHotbarService)
					{
						globalHotbarService.SaveCharacterSlots(UID.op_Implicit(_character.UID));
					}
					_hotbars.ClearChanges();
				}
			}
			catch (Exception ex)
			{
				Logger.LogException("Failed to Save Hotbar changes.", ex);
			}
		}

		private void ScaleHotbars(int scaleAmount)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_hotbars == (Object)null))
			{
				float num = (float)scaleAmount / 100f;
				((Component)_hotbars).transform.localScale = new Vector3(num, num, 1f);
			}
		}

		private void SwapCanvasGroup()
		{
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Expected O, but got Unknown
			try
			{
				QuickSlotControllerSwitcher val = ((IEnumerable<QuickSlotControllerSwitcher>)((Component)_characterUI).GetComponentsInChildren<QuickSlotControllerSwitcher>()).FirstOrDefault((Func<QuickSlotControllerSwitcher, bool>)((QuickSlotControllerSwitcher q) => ((Object)q).name == "QuickSlot"));
				if ((Object)(object)val == (Object)null)
				{
					Logger.LogWarning("[HotbarService] QuickSlotControllerSwitcher not found!");
					return;
				}
				CanvasGroup privateField = ReflectionExtensions.GetPrivateField<QuickSlotControllerSwitcher, CanvasGroup>(val, "m_keyboardQuickSlots");
				CanvasGroup privateField2 = ReflectionExtensions.GetPrivateField<QuickSlotControllerSwitcher, CanvasGroup>(val, "m_gamepadQuickSlots");
				if (_hotbars.VanillaSuppressionTargets == null)
				{
					_hotbars.VanillaSuppressionTargets = new List<GameObject>();
				}
				_hotbars.VanillaSuppressionTargets.Clear();
				if ((Object)(object)privateField != (Object)null)
				{
					((Component)privateField).gameObject.SetActive(false);
					privateField.alpha = 0f;
					_hotbars.VanillaSuppressionTargets.Add(((Component)privateField).gameObject);
				}
				GameObject val2 = new GameObject("DummyKeyboardSlots");
				val2.transform.SetParent(((Component)val).transform);
				CanvasGroup val3 = val2.AddComponent<CanvasGroup>();
				val3.alpha = 0f;
				val3.blocksRaycasts = false;
				val3.interactable = false;
				ReflectionExtensions.SetPrivateField<QuickSlotControllerSwitcher, CanvasGroup>(val, "m_keyboardQuickSlots", val3);
				if (_hotbars.VanillaOverlayTargets == null)
				{
					_hotbars.VanillaOverlayTargets = new List<CanvasGroup>();
				}
				_hotbars.VanillaOverlayTargets.Clear();
				if ((Object)(object)privateField2 != (Object)null)
				{
					_hotbars.VanillaOverlayTargets.Add(privateField2);
				}
				Logger.LogDebug($"[HotbarService] SwapCanvasGroup Complete. KeyboardGroup found: {(Object)(object)privateField != (Object)null}, GamepadGroup found: {(Object)(object)privateField2 != (Object)null}. Swapped to Dummy.");
			}
			catch (Exception ex)
			{
				Logger.LogException("Failed to populate VanillaOverlayTargets or disable QuickSlots.", ex);
			}
		}

		public void DisableKeyboardQuickslots(KeyboardQuickSlotPanel keyboard)
		{
			if ((Object)(object)keyboard != (Object)null && ((Component)keyboard).gameObject.activeSelf)
			{
				IModifLogger logger = Logger;
				int? obj;
				if (keyboard == null)
				{
					obj = null;
				}
				else
				{
					CharacterUI characterUI = ((UIElement)keyboard).CharacterUI;
					obj = ((characterUI != null) ? new int?(characterUI.RewiredID) : null);
				}
				logger.LogDebug($"Disabling Keyboard QuickSlots for RewiredID {obj}.");
				((Component)keyboard).gameObject.SetActive(false);
			}
		}

		private IHotbarProfile GetOrCreateActiveProfile()
		{
			IActionUIProfile activeProfile = _profileService.GetActiveProfile();
			IHotbarProfile profile = _hotbarProfileService.GetProfile();
			Logger.LogDebug("Got or Created Active Profile '" + activeProfile.Name + "'");
			return profile;
		}

		public void AssignSlotActions()
		{
			AssignSlotActions(GetOrCreateActiveProfile());
		}

		public void AssignSlotActions(IHotbarProfile profile)
		{
			Logger.LogDebug(string.Format("{0}_{1}: Assigning Slot Actions.", "HotbarService", InstanceID));
			_saveDisabled = true;
			_isConfiguring = true;
			try
			{
				for (int i = 0; i < profile.Hotbars.Count; i++)
				{
					for (int j = 0; j < profile.Hotbars[i].Slots.Count; j++)
					{
						try
						{
							SlotData slotData = profile.Hotbars[i].Slots[j] as SlotData;
							ActionSlot val = _hotbars.Controller.GetActionSlots()[i][j];
							bool flag = false;
							if (slotData != null && (Object)(object)val != (Object)null && _slotData.TryGetItemSlotAction(slotData, profile.CombatMode, out var slotAction))
							{
								try
								{
									val.Controller.AssignSlotAction(slotAction, false);
									flag = true;
								}
								catch (Exception ex)
								{
									Logger.LogException($"Failed to assign slot action '{((slotAction != null) ? slotAction.DisplayName : null)}' to Bar {i}, Slot Index {j}.", ex);
								}
							}
							if (!flag)
							{
								val.Controller.AssignEmptyAction();
							}
						}
						catch (Exception ex2)
						{
							Logger.LogException($"Failed to assign action to slot {i}_{j}.", ex2);
						}
					}
				}
				SetProfileHotkeys(profile);
				if (!_isProfileInit)
				{
					_isProfileInit = true;
				}
				_hotbars.Controller.Refresh();
			}
			finally
			{
				Logger.LogDebug("Clearing Hotbar Change Flag and enabling save.");
				_hotbars.ClearChanges();
				_saveDisabled = false;
				_isConfiguring = false;
			}
		}

		private void SetProfileHotkeys(IHotbarProfile profile)
		{
			KeyboardMap map = _player.controllers.maps.GetMap<KeyboardMap>(0, 131000, 0);
			MouseMap map2 = _player.controllers.maps.GetMap<MouseMap>(0, 131000, 0);
			if (map == null || map2 == null)
			{
				Logger.LogWarning($"SetProfileHotkeys: Controller maps not found for player {_player.id}. Skipping hotkey configuration. (KeyMap: {map != null}, MouseMap: {map2 != null})");
				return;
			}
			HotbarProfileData profileData = (HotbarProfileData)(object)profile;
			HotbarProfileData hotbarProfileData = profileData;
			ActionElementMap? obj = ((IEnumerable<ActionElementMap>)((ControllerMap)map).ButtonMaps).FirstOrDefault((Func<ActionElementMap, bool>)((ActionElementMap m) => m.actionId == profileData.NextRewiredActionId));
			hotbarProfileData.NextHotkey = ((obj != null) ? obj.elementIdentifierName : null);
			if (string.IsNullOrWhiteSpace(profileData.NextHotkey))
			{
				HotbarProfileData hotbarProfileData2 = profileData;
				ActionElementMap? obj2 = ((IEnumerable<ActionElementMap>)((ControllerMap)map2).ButtonMaps).FirstOrDefault((Func<ActionElementMap, bool>)((ActionElementMap m) => m.actionId == profileData.NextRewiredActionId));
				hotbarProfileData2.NextHotkey = ((obj2 != null) ? obj2.elementIdentifierName : null);
			}
			if (string.IsNullOrWhiteSpace(profileData.NextHotkey) && ((ControllerMap)map2).AllMaps.Any((ActionElementMap m) => m.a

ModifAmorphic.Outward.Shared.v0_0_0_9.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Localizer;
using ModifAmorphic.Outward.Config.Extensions;
using ModifAmorphic.Outward.Config.Models;
using ModifAmorphic.Outward.Events;
using ModifAmorphic.Outward.Extensions;
using ModifAmorphic.Outward.GameObjectResources;
using ModifAmorphic.Outward.Internal;
using ModifAmorphic.Outward.Localization;
using ModifAmorphic.Outward.Logging;
using ModifAmorphic.Outward.Models;
using ModifAmorphic.Outward.Modules.CharacterMods;
using ModifAmorphic.Outward.Modules.Crafting;
using ModifAmorphic.Outward.Modules.Crafting.CompatibleIngredients;
using ModifAmorphic.Outward.Modules.Crafting.Models;
using ModifAmorphic.Outward.Modules.Crafting.Patches;
using ModifAmorphic.Outward.Modules.Crafting.Services;
using ModifAmorphic.Outward.Modules.Items;
using ModifAmorphic.Outward.Modules.Items.Models;
using ModifAmorphic.Outward.Modules.Items.Patches;
using ModifAmorphic.Outward.Modules.Localization;
using ModifAmorphic.Outward.Modules.Merchants;
using ModifAmorphic.Outward.Modules.QuickSlots;
using ModifAmorphic.Outward.Modules.QuickSlots.KeyBindings;
using ModifAmorphic.Outward.Modules.QuickSlots.KeyBindings.Services;
using ModifAmorphic.Outward.Patches;
using Rewired;
using SideLoader;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("ModifAmorphic.Outward")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a580093fb59052c6205677075b91d046d390cb6a")]
[assembly: AssemblyProduct("ModifAmorphic.Outward")]
[assembly: AssemblyTitle("ModifAmorphic.Outward.Shared.v0_0_0_9")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ModifAmorphic.Outward
{
	internal static class DefaultLoggerInfo
	{
		public const string ModId = "modifamorphic.outward.shared";

		public const string ModName = "ModifAmorphic";

		public const LogLevel DebugLogLevel = LogLevel.Trace;
	}
	public static class ItemTags
	{
		private static Tag _equipmentTag;

		private static Tag _weaponTag;

		private static Tag _bowTag;

		private static Tag _pistolTag;

		private static Tag _chakramTag;

		private static Tag _helmetTag;

		private static Tag _armorTag;

		private static Tag _bootsTag;

		private static Tag _dagueTag;

		private static Tag _trinketTag;

		private static Tag _lanternTag;

		private static Tag _lexiconTag;

		private static Tag _backpackTag;

		private static Tag _enchantIngredientsTag;

		public static Tag EquipmentTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _equipmentTag)).IsSet)
				{
					_equipmentTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("13"));
				}
				return _equipmentTag;
			}
		}

		public static Tag WeaponTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _weaponTag)).IsSet)
				{
					_weaponTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("1"));
				}
				return _weaponTag;
			}
		}

		public static Tag BowTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _bowTag)).IsSet)
				{
					_bowTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("8"));
				}
				return _bowTag;
			}
		}

		public static Tag PistolTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _pistolTag)).IsSet)
				{
					_pistolTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("21"));
				}
				return _pistolTag;
			}
		}

		public static Tag ChakramTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _chakramTag)).IsSet)
				{
					_chakramTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("160"));
				}
				return _chakramTag;
			}
		}

		public static Tag HelmetTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _helmetTag)).IsSet)
				{
					_helmetTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("14"));
				}
				return _helmetTag;
			}
		}

		public static Tag ArmorTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _armorTag)).IsSet)
				{
					_armorTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("15"));
				}
				return _armorTag;
			}
		}

		public static Tag BootsTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _bootsTag)).IsSet)
				{
					_bootsTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("16"));
				}
				return _bootsTag;
			}
		}

		public static Tag DagueTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _dagueTag)).IsSet)
				{
					_dagueTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("22"));
				}
				return _dagueTag;
			}
		}

		public static Tag TrinketTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _trinketTag)).IsSet)
				{
					_trinketTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("17"));
				}
				return _trinketTag;
			}
		}

		public static Tag LanternTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _lanternTag)).IsSet)
				{
					_lanternTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("37"));
				}
				return _lanternTag;
			}
		}

		public static Tag LexiconTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _lexiconTag)).IsSet)
				{
					_lexiconTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("161"));
				}
				return _lexiconTag;
			}
		}

		public static Tag BackpackTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _backpackTag)).IsSet)
				{
					_backpackTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("68"));
				}
				return _backpackTag;
			}
		}

		public static Tag EnchantIngredientsTag
		{
			get
			{
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				if (!((Tag)(ref _enchantIngredientsTag)).IsSet)
				{
					_enchantIngredientsTag = TagSourceManager.Instance.GetTag(UID.op_Implicit("54"));
				}
				return _enchantIngredientsTag;
			}
		}
	}
	public class ServicesProvider
	{
		private readonly ConcurrentDictionary<Type, Delegate> _serviceFactories = new ConcurrentDictionary<Type, Delegate>();

		private readonly NullLogger nullLogger = new NullLogger();

		public BaseUnityPlugin UnityPlugin => GetService<BaseUnityPlugin>();

		private IModifLogger Logger
		{
			get
			{
				IModifLogger result;
				if (!TryGetLogger(out var logger))
				{
					IModifLogger modifLogger = nullLogger;
					result = modifLogger;
				}
				else
				{
					result = logger;
				}
				return result;
			}
		}

		public ServicesProvider(BaseUnityPlugin unityPlugin)
		{
			AddSingleton<BaseUnityPlugin>(unityPlugin);
		}

		public ServicesProvider AddSingleton<T>(T serviceInstance)
		{
			_serviceFactories.TryAdd(typeof(T), (Func<T>)(() => serviceInstance));
			return this;
		}

		public ServicesProvider AddFactory<T>(Func<T> serviceFactory)
		{
			_serviceFactories.TryAdd(typeof(T), serviceFactory);
			return this;
		}

		public Func<T> GetServiceFactory<T>()
		{
			Logger.LogTrace("ServicesProvider::GetServiceFactory<T>: Type: " + typeof(T).Name);
			return (Func<T>)_serviceFactories[typeof(T)];
		}

		public T GetService<T>()
		{
			Logger.LogTrace("ServicesProvider::GetService<T>: Type: " + typeof(T).Name);
			return (T)_serviceFactories[typeof(T)].DynamicInvoke();
		}

		public object GetService(Type type)
		{
			Logger.LogTrace("ServicesProvider::GetService: Type: " + type.Name);
			return _serviceFactories[type].DynamicInvoke();
		}

		public List<T> GetServices<T>()
		{
			Logger.LogTrace("ServicesProvider::GetServices<T>: Type: " + typeof(T).Name);
			return (from kvp in _serviceFactories
				where typeof(T).IsAssignableFrom(kvp.Key)
				select (T)kvp.Value.DynamicInvoke()).ToList();
		}

		public List<Func<T>> GetServiceFactories<T>()
		{
			Logger.LogTrace("ServicesProvider::GetServiceFactories<T>: Type: " + typeof(T).Name);
			return (from kvp in _serviceFactories
				where typeof(T).IsAssignableFrom(kvp.Key)
				select (Func<T>)kvp.Value).ToList();
		}

		public bool TryGetService<T>(out T service)
		{
			Logger.LogTrace("ServicesProvider::TryGetService<T>: Type: " + typeof(T).Name);
			service = default(T);
			if (!_serviceFactories.TryGetValue(typeof(T), out var value))
			{
				return false;
			}
			service = (T)value.DynamicInvoke();
			return !EqualityComparer<T>.Default.Equals(service, default(T));
		}

		private bool TryGetLogger(out IModifLogger logger)
		{
			logger = null;
			if (!_serviceFactories.TryGetValue(typeof(IModifLogger), out var value))
			{
				return false;
			}
			logger = (IModifLogger)value.DynamicInvoke();
			return logger != null;
		}
	}
}
namespace ModifAmorphic.Outward.Patches
{
	[HarmonyPatch(typeof(LocalizationManager))]
	public static class LocalizationManagerPatches
	{
		public delegate void RegisterItemLocalizations(ref Dictionary<int, ItemLocalization> itemLocalizations);

		[MultiLogger]
		private static IModifLogger Logger { get; set; } = new NullLogger();


		public static event Action<LocalizationManager> AwakeAfter;

		public static event Action<LocalizationManager> LoadAfter;

		public static event RegisterItemLocalizations LoadItemLocalizationAfter;

		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void AwakePostfix(LocalizationManager __instance)
		{
			try
			{
				Logger.LogTrace(string.Format("{0}::{1}(): Invoked. Invoking {2}({3}). AwakeAfter null: {4}", "LocalizationManagerPatches", "AwakePostfix", "AwakePostfix", "LocalizationManager", LocalizationManagerPatches.AwakeAfter == null));
				LocalizationManagerPatches.AwakeAfter?.Invoke(__instance);
			}
			catch (Exception ex)
			{
				Logger.LogException("LocalizationManagerPatches::AwakePostfix(): Exception Invoking AwakePostfix(LocalizationManager).", ex);
			}
		}

		[HarmonyPatch("Load")]
		[HarmonyPostfix]
		private static void LoadPostfix(LocalizationManager __instance)
		{
			try
			{
				Logger.LogTrace("LocalizationManagerPatches::LoadPostfix(): Invoked. Invoking LoadAfter(LocalizationManager).");
				LocalizationManagerPatches.LoadAfter?.Invoke(__instance);
			}
			catch (Exception ex)
			{
				Logger.LogException("LocalizationManagerPatches::LoadPostfix(): Exception Invoking LoadAfter(LocalizationManager).", ex);
			}
		}

		[HarmonyPatch("LoadItemLocalization")]
		[HarmonyPostfix]
		private static void LoadItemLocalizationPostfix(ref Dictionary<int, ItemLocalization> ___m_itemLocalization)
		{
			try
			{
				Logger.LogTrace("LocalizationManagerPatches::LoadItemLocalizationPostfix(): Invoked. Invoking LoadItemLocalizationPostfix(Dictionary)");
				LocalizationManagerPatches.LoadItemLocalizationAfter?.Invoke(ref ___m_itemLocalization);
			}
			catch (Exception ex)
			{
				Logger.LogException("LocalizationManagerPatches::LoadItemLocalizationPostfix(): Exception Invoking LoadItemLocalizationPostfix(Dictionary).", ex);
			}
		}
	}
}
namespace ModifAmorphic.Outward.Modules
{
	internal interface IModifModule
	{
		HashSet<Type> PatchDependencies { get; }

		HashSet<Type> DepsWithMultiLogger { get; }

		HashSet<Type> EventSubscriptions { get; }
	}
	internal abstract class ModifModule
	{
		public IModifLogger Logger { get; }

		public ModifModule(IModifLogger modifLogger)
		{
			Logger = modifLogger;
		}
	}
	public static class ModifModules
	{
		private static ModuleService _lazyService;

		private static ModuleService ModuleService
		{
			get
			{
				if (_lazyService == null)
				{
					_lazyService = new ModuleService();
				}
				return _lazyService;
			}
		}

		public static QuickSlotExtender GetQuickSlotExtenderModule(string modId)
		{
			return ModuleService.GetModule(modId, () => new QuickSlotExtender(new QsMenuExtender(() => LoggerFactory.GetLogger(modId)), () => LoggerFactory.GetLogger(modId)));
		}

		public static CharacterInstances GetCharacterInstancesModule(string modId)
		{
			return ModuleService.GetModule(modId, () => new CharacterInstances(() => LoggerFactory.GetLogger(modId)));
		}

		public static PreFabricator GetPreFabricatorModule(string modId)
		{
			ItemPrefabService itemPrefabService = new ItemPrefabService(modId, new ModifGoService(() => LoggerFactory.GetLogger(modId)), () => ResourcesPrefabManager.Instance, () => LoggerFactory.GetLogger(modId));
			return ModuleService.GetModule(modId, () => new PreFabricator(modId, itemPrefabService, () => LoggerFactory.GetLogger(modId)));
		}

		public static ItemVisualizer GetItemVisualizerModule(string modId)
		{
			IconService iconService = new IconService(modId, new ModifGoService(() => LoggerFactory.GetLogger(modId)), () => LoggerFactory.GetLogger(modId));
			return ModuleService.GetModule(modId, () => new ItemVisualizer(() => ResourcesPrefabManager.Instance, () => ItemManager.Instance, iconService, () => LoggerFactory.GetLogger(modId)));
		}

		public static MerchantModule GetMerchantModule(string modId)
		{
			return ModuleService.GetModule(modId, () => new MerchantModule(() => LoggerFactory.GetLogger(modId)));
		}

		public static CustomCraftingModule GetCustomCraftingModule(string modId)
		{
			CraftingMenuUIService craftingMenuUIService = new CraftingMenuUIService(() => LoggerFactory.GetLogger(modId));
			CraftingMenuEvents craftingMenuEvents = new CraftingMenuEvents();
			return ModuleService.GetModule(modId, () => new CustomCraftingModule(new CraftingMenuUIService(() => LoggerFactory.GetLogger(modId)), new RecipeDisplayService(() => LoggerFactory.GetLogger(modId)), new CustomRecipeService(() => RecipeManager.Instance, () => LoggerFactory.GetLogger(modId)), new CustomCraftingService(craftingMenuEvents, () => LoggerFactory.GetLogger(modId)), craftingMenuEvents, () => LoggerFactory.GetLogger(modId)));
		}

		public static LocalizationModule GetLocalizationModule(string modId)
		{
			return ModuleService.GetModule(modId, () => new LocalizationModule(() => LoggerFactory.GetLogger(modId)));
		}
	}
	internal class ModuleService
	{
		private Harmony _patcher = null;

		private readonly ConcurrentDictionary<Type, byte> _patchedTypes = new ConcurrentDictionary<Type, byte>();

		private readonly ConcurrentDictionary<Type, byte> _subscriberTypes = new ConcurrentDictionary<Type, byte>();

		private readonly ConcurrentDictionary<string, ConcurrentDictionary<Type, IModifModule>> _instances = new ConcurrentDictionary<string, ConcurrentDictionary<Type, IModifModule>>();

		internal T GetModule<T>(string modId, Func<T> factory) where T : class, IModifModule
		{
			ConcurrentDictionary<Type, IModifModule> orAdd = _instances.GetOrAdd(modId, new ConcurrentDictionary<Type, IModifModule>());
			return orAdd.GetOrAdd(typeof(T), (Type x) => CreateModule(modId, factory)) as T;
		}

		private IModifModule CreateModule<T>(string modId, Func<T> factory) where T : class, IModifModule
		{
			T module = factory();
			LoggerEvents.LoggerCreated += delegate((string ModId, IModifLogger Logger) args)
			{
				if (args.ModId == modId)
				{
					ConfigureMultiLoggersForDependencies<T>(modId, module, () => LoggerFactory.GetLogger(modId));
				}
			};
			ConfigureMultiLoggersForDependencies<T>(modId, module, () => LoggerFactory.GetLogger(modId));
			ApplyPatches(module);
			ConfigureSubscriptions(module, () => LoggerFactory.GetLogger(modId));
			return module;
		}

		internal IModifModule ConfigureSubscriptions(IModifModule module, Func<IModifLogger> getLogger)
		{
			foreach (Type eventSubscription in module.EventSubscriptions)
			{
				if (!_subscriberTypes.ContainsKey(eventSubscription))
				{
					_subscriberTypes.TryAdd(eventSubscription, 0);
					EventSubscriberService.RegisterClassSubscriptions(eventSubscription, getLogger());
				}
			}
			return module;
		}

		private void ConfigureMultiLoggersForDependencies<T>(string modId, IModifModule module, Func<IModifLogger> loggerFactory)
		{
			foreach (Type item in module.DepsWithMultiLogger)
			{
				PatchLoggerRegisterService.AddOrUpdatePatchLogger(item, modId, loggerFactory);
			}
		}

		private IModifModule ApplyPatches(IModifModule module)
		{
			foreach (Type patchDependency in module.PatchDependencies)
			{
				if (!_patchedTypes.ContainsKey(patchDependency))
				{
					_patchedTypes.TryAdd(patchDependency, 0);
					GetModPatcher().PatchAll(patchDependency);
					if (patchDependency == typeof(LocalizationManagerPatches))
					{
						LocalizationService.Init();
					}
				}
			}
			return module;
		}

		private Harmony GetModPatcher()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			//IL_001d: Expected O, but got Unknown
			Harmony obj = _patcher;
			if (obj == null)
			{
				Harmony val = new Harmony("modifamorphic.outward");
				Harmony val2 = val;
				_patcher = val;
				obj = val2;
			}
			return obj;
		}
	}
}
namespace ModifAmorphic.Outward.Modules.QuickSlots
{
	public class QuickSlotExtender : IModifModule
	{
		private readonly Func<IModifLogger> _loggerFactory;

		private readonly QsMenuExtender _qsMenuExtender;

		private IModifLogger Logger => _loggerFactory();

		public HashSet<Type> PatchDependencies
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(CharacterQuickSlotManagerPatches));
				hashSet.Add(typeof(KeyboardQuickSlotPanelPatches));
				hashSet.Add(typeof(LocalCharacterControlPatches));
				hashSet.Add(typeof(QsLocalizationManagerPatches));
				return hashSet;
			}
		}

		public HashSet<Type> EventSubscriptions
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(CharacterQuickSlotManagerPatches));
				hashSet.Add(typeof(KeyboardQuickSlotPanelPatches));
				hashSet.Add(typeof(LocalCharacterControlPatches));
				hashSet.Add(typeof(QsLocalizationManagerPatches));
				return hashSet;
			}
		}

		public HashSet<Type> DepsWithMultiLogger
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(CharacterQuickSlotManagerPatches));
				hashSet.Add(typeof(KeyboardQuickSlotPanelPatches));
				hashSet.Add(typeof(LocalCharacterControlPatches));
				hashSet.Add(typeof(QsLocalizationManagerPatches));
				return hashSet;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal QuickSlotExtender(QsMenuExtender qsMenuExtender, Func<IModifLogger> loggerFactory)
		{
			_loggerFactory = loggerFactory;
			_qsMenuExtender = qsMenuExtender;
		}

		public void ExtendQuickSlots(int extendAmount, string menuDescriptionFormat)
		{
			List<ExtendedQuickSlot> list = _qsMenuExtender.ExtendQuickSlots(extendAmount, menuDescriptionFormat);
			CharacterQuickSlotManagerPatches.Configure(list.Count);
			KeyboardQuickSlotPanelPatches.Configure(list.Count, list.First().QuickSlotId);
			LocalCharacterControlPatches.Configure(list);
			QsLocalizationManagerPatches.Configure(list);
		}
	}
}
namespace ModifAmorphic.Outward.Modules.QuickSlots.KeyBindings
{
	internal class ExtendedQuickSlot
	{
		public int QuickSlotId { get; set; }

		public string ActionName { get; set; }

		public string ActionKey { get; set; }

		public string ActionDescription { get; set; }
	}
	internal class MoreQuickslotsLocalizationListener : ILocalizeListener
	{
		private readonly Dictionary<string, string> qsLocalizations;

		private readonly IModifLogger logger;

		public MoreQuickslotsLocalizationListener(Dictionary<string, string> qsLocalizations, IModifLogger logger)
		{
			this.logger = logger;
			this.qsLocalizations = qsLocalizations;
		}

		public void Localize()
		{
			logger.LogInfo(string.Format("{0} Adding {1} new localizations for quickslots.", "MoreQuickslotsLocalizationListener", qsLocalizations.Count));
			Dictionary<string, string> generalLocalizations = LocalizationManager.Instance.GetGeneralLocalizations();
			StringBuilder stringBuilder = new StringBuilder();
			foreach (KeyValuePair<string, string> qsLocalization in qsLocalizations)
			{
				if (!generalLocalizations.ContainsKey(qsLocalization.Key))
				{
					generalLocalizations.Add(qsLocalization.Key, qsLocalization.Value);
					stringBuilder.AppendLine("\tname: " + qsLocalization.Key + ", desc: " + qsLocalization.Value);
				}
			}
			logger.LogDebug(string.Format("{0} Localizations Added:\n{1}.", "MoreQuickslotsLocalizationListener", stringBuilder));
			LocalizationManager.Instance.SetGeneralLocalizations(generalLocalizations);
		}
	}
	[HarmonyPatch(typeof(CharacterQuickSlotManager), "Awake")]
	internal static class CharacterQuickSlotManagerPatches
	{
		private static int _quickslotsToAdd;

		private static bool _isAwakened = false;

		[MultiLogger]
		private static IModifLogger Logger { get; set; } = new NullLogger();


		public static void Configure(int qsToAdd)
		{
			if (_isAwakened)
			{
				throw new InvalidOperationException("CharacterQuickSlotManagerPatches.Configure cannot be called after the CharacterQuickSlotManager's Awake method has been called.");
			}
			_quickslotsToAdd = qsToAdd;
		}

		[HarmonyPrefix]
		public static void OnAwake_AddQuickSlots(CharacterQuickSlotManager __instance)
		{
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Expected O, but got Unknown
			_isAwakened = true;
			if (_quickslotsToAdd < 1)
			{
				return;
			}
			try
			{
				Transform val = ((Component)__instance).transform.Find("QuickSlots");
				int num = val.childCount + 1;
				Logger.LogDebug($"Adding {_quickslotsToAdd} extra quickslots to the CharacterQuickSlotManager QuickSlots transform. Starting with Id {num}.");
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.AppendLine("\n\t//////*************quickslotTransform Start*************//////");
				for (int i = 0; i < val.childCount; i++)
				{
					Transform child = val.GetChild(i);
					QuickSlot component = ((Component)child).gameObject.GetComponent<QuickSlot>();
					stringBuilder.AppendLine($"\tIndex: {i}; GameObject Name: {((Object)((Component)child).gameObject).name}; QuickSlot Name: {((Object)component).name}");
				}
				stringBuilder.AppendLine("\t//////*************quickslotTransform End*************//////");
				Logger.LogTrace(stringBuilder.ToString());
				for (int j = 0; j < _quickslotsToAdd; j++)
				{
					GameObject val2 = new GameObject($"ExtraQuickSlot_{j}");
					Logger.LogDebug(string.Format("{0}(): created new GameObject(ExtraQuickSlot_{1}).  gameObject.name: '{2}'", "OnAwake_AddQuickSlots", j, ((Object)val2).name));
					QuickSlot val3 = val2.AddComponent<QuickSlot>();
					((Object)val3).name = (num + j).ToString();
					val2.transform.SetParent(val);
				}
				val.SetParent(((Component)__instance).transform);
				Transform val4 = ((Component)__instance).transform.Find("QuickSlots");
				stringBuilder = new StringBuilder();
				stringBuilder.AppendLine("\n\t//////*************quickslotTransformAfterSetParent after quickslotTransform.SetParent(self.transform) Start*************//////");
				if ((Object)(object)val4 != (Object)null)
				{
					for (int k = 0; k < val4.childCount; k++)
					{
						Transform child2 = val4.GetChild(k);
						object obj;
						if (child2 == null)
						{
							obj = null;
						}
						else
						{
							GameObject gameObject = ((Component)child2).gameObject;
							obj = ((gameObject != null) ? gameObject.GetComponent<QuickSlot>() : null);
						}
						QuickSlot val5 = (QuickSlot)obj;
						StringBuilder stringBuilder2 = stringBuilder;
						object[] obj2 = new object[4]
						{
							k,
							(child2 != null) ? ((Object)child2).name : null,
							null,
							null
						};
						object obj3;
						if (child2 == null)
						{
							obj3 = null;
						}
						else
						{
							GameObject gameObject2 = ((Component)child2).gameObject;
							obj3 = ((gameObject2 != null) ? ((Object)gameObject2).name : null);
						}
						obj2[2] = obj3;
						obj2[3] = ((val5 != null) ? ((Object)val5).name : null);
						stringBuilder2.AppendLine(string.Format("\tIndex: {0}; Child Name: {1}; GameObject Name: {2}; QuickSlot Name: {3}", obj2));
					}
				}
				else
				{
					stringBuilder.AppendLine("\tquickslotTransformAfterSetParent null.  No GameObjects.");
				}
				stringBuilder.AppendLine("\t//////*************quickslotTransformAfterSetParent after quickslotTransform.SetParent(self.transform) End*************//////");
				Logger.LogDebug(stringBuilder.ToString());
				Logger.LogDebug("OnAwake_AddQuickSlots(): complete.");
			}
			catch (Exception ex)
			{
				Logger.LogException("OnAwake_AddQuickSlots() error.", ex);
				throw;
			}
		}
	}
	[HarmonyPatch(typeof(KeyboardQuickSlotPanel), "InitializeQuickSlotDisplays")]
	internal static class KeyboardQuickSlotPanelPatches
	{
		private static int _quickslotsToAdd;

		private static int _quickslotStartId;

		private static bool _isInitialized = false;

		[MultiLogger]
		private static IModifLogger Logger { get; set; } = new NullLogger();


		public static void Configure(int qsToAdd, int qsStartId)
		{
			if (_isInitialized)
			{
				throw new InvalidOperationException("KeyboardQuickSlotPanelPatches.Configure cannot be called after the KeyboardQuickSlotPanel's InitializeQuickSlotDisplays method has been called.");
			}
			_quickslotsToAdd = qsToAdd;
			_quickslotStartId = qsStartId;
		}

		[HarmonyPrefix]
		public static void OnInitializeQuickSlotDisplays_AddExtraSlots(KeyboardQuickSlotPanel __instance)
		{
			_isInitialized = true;
			if (_quickslotsToAdd < 1)
			{
				return;
			}
			try
			{
				int num = __instance.DisplayOrder.Length;
				int num2 = __instance.DisplayOrder.Length + _quickslotsToAdd;
				int quickslotStartId = _quickslotStartId;
				Array.Resize(ref __instance.DisplayOrder, num2);
				Logger.LogTrace(string.Format("{0}(): exStartIndex={1}; exEndIndex={2}; Starting Quickslot Id={3})", "OnInitializeQuickSlotDisplays_AddExtraSlots", num, num2, quickslotStartId));
				for (int i = num; i < num2; i++)
				{
					__instance.DisplayOrder[i] = (QuickSlotIDs)(quickslotStartId++);
				}
			}
			catch (Exception ex)
			{
				Logger.LogException("OnInitializeQuickSlotDisplays_AddExtraSlots() error.", ex);
				throw;
			}
		}
	}
	[HarmonyPatch]
	internal static class LocalCharacterControlPatches
	{
		private static Dictionary<int, RewiredInputs> _playerInputManager = new Dictionary<int, RewiredInputs>();

		private static IEnumerable<ExtendedQuickSlot> _exQuickSlots = new List<ExtendedQuickSlot>();

		[MultiLogger]
		private static IModifLogger Logger { get; set; } = new NullLogger();


		public static void Configure(IEnumerable<ExtendedQuickSlot> exQuickSlots)
		{
			_exQuickSlots = exQuickSlots;
		}

		[HarmonyPatch(typeof(ControlsInput), "Setup")]
		[HarmonyPostfix]
		public static void OnControlsInputSetup_SetPlayerInputManager()
		{
			_playerInputManager = ((ControlsInput)null).GetPlayerInputManager();
			IList<InputCategory> actionCategories = ReInput.mapping.ActionCategories;
			string text = string.Empty;
			foreach (InputCategory item in actionCategories)
			{
				text += $"Category ID: {item.id}, Name: {item.name}, DescriptiveName: {item.descriptiveName}\n";
				IEnumerable<InputAction> enumerable = ReInput.mapping.ActionsInCategory(item.id);
				foreach (InputAction item2 in enumerable)
				{
					text += $"\tAction Id: {item2.id}, Name: {item2.name}, DescriptiveName: {item2.descriptiveName}\n";
				}
			}
			Logger.LogTrace(text);
		}

		[HarmonyPatch(typeof(LocalCharacterControl), "UpdateQuickSlots")]
		[HarmonyPostfix]
		public static void OnUpdateQuickSlots_CheckForButtonPresses(LocalCharacterControl __instance)
		{
			if (_exQuickSlots.Count() < 1)
			{
				return;
			}
			if ((Object)(object)((CharacterControl)__instance).Character == (Object)null || (Object)(object)((CharacterControl)__instance).Character.QuickSlotMngr == (Object)null)
			{
				Logger?.LogTrace("LocalCharacterControl.UpdateQuickSlots - Character or Character.QuickSlotMng was null.");
				return;
			}
			try
			{
				int playerID = ((CharacterControl)__instance).Character.OwnerPlayerSys.PlayerID;
				if (AnyQuickSlotInstantButtonsDown(playerID))
				{
					Logger?.LogTrace("LocalCharacterControl.UpdateQuickSlots - Built in quickslot button was pressed.  Exiting.");
					return;
				}
				int firstExQuickSlotInstantDown = GetFirstExQuickSlotInstantDown(playerID);
				if (firstExQuickSlotInstantDown > 0)
				{
					Logger?.LogTrace($"Triggering Ex Quickslot #{firstExQuickSlotInstantDown}");
					((CharacterControl)__instance).Character.QuickSlotMngr.QuickSlotInput(firstExQuickSlotInstantDown - 1);
				}
			}
			catch (Exception ex)
			{
				Logger?.LogException("Exception in LocalCharacterControlPatches.OnUpdateQuickSlots_CheckForButtonPresses().", ex);
				throw;
			}
		}

		public static bool AnyQuickSlotInstantButtonsDown(int _playerID)
		{
			return ControlsInput.QuickSlotInstant1(_playerID) || ControlsInput.QuickSlotInstant2(_playerID) || ControlsInput.QuickSlotInstant3(_playerID) || (ControlsInput.QuickSlotInstant4(_playerID) | ControlsInput.QuickSlotInstant5(_playerID)) || ControlsInput.QuickSlotInstant6(_playerID) || ControlsInput.QuickSlotInstant7(_playerID) || ControlsInput.QuickSlotInstant8(_playerID);
		}

		public static int GetFirstExQuickSlotInstantDown(int playerID)
		{
			foreach (ExtendedQuickSlot exQuickSlot in _exQuickSlots)
			{
				if (QuickSlotInstantN(playerID, exQuickSlot.ActionName))
				{
					return exQuickSlot.QuickSlotId;
				}
			}
			return -1;
		}

		public static bool QuickSlotInstantN(int playerId, string actionName)
		{
			return _playerInputManager[playerId].GetButtonDown(actionName);
		}
	}
	[HarmonyPatch(typeof(LocalizationManager), "Awake")]
	internal static class QsLocalizationManagerPatches
	{
		private static readonly List<ILocalizeListener> _customLocalizationListeners = new List<ILocalizeListener>();

		[MultiLogger]
		private static IModifLogger Logger { get; set; } = new NullLogger();


		public static void Configure(IEnumerable<ExtendedQuickSlot> extendedQuickSlots)
		{
			Dictionary<string, string> qsLocalizations = extendedQuickSlots.ToDictionary((ExtendedQuickSlot x) => x.ActionKey, (ExtendedQuickSlot x) => x.ActionDescription);
			MoreQuickslotsLocalizationListener item = new MoreQuickslotsLocalizationListener(qsLocalizations, Logger);
			_customLocalizationListeners.Add((ILocalizeListener)(object)item);
		}

		[HarmonyPostfix]
		public static void AddCustomLocalizations(LocalizationManager __instance)
		{
			foreach (ILocalizeListener customLocalizationListener in _customLocalizationListeners)
			{
				__instance.RegisterLocalizeElement(customLocalizationListener);
			}
		}
	}
}
namespace ModifAmorphic.Outward.Modules.QuickSlots.KeyBindings.Services
{
	internal class QsMenuExtender
	{
		private readonly Func<IModifLogger> _loggerFactory;

		private const string ActionNamePrefix = "QS_Instant";

		private const string ActionKeyPrefix = "InputAction_";

		private const string MenuSlotNoKey = "{ExtraSlotNumber}";

		private const string MenuDescriptionDefaultFormat = "Ex Quick Slot {ExtraSlotNumber}";

		private IModifLogger Logger => _loggerFactory();

		public QsMenuExtender(Func<IModifLogger> loggerFactory)
		{
			_loggerFactory = loggerFactory;
		}

		public List<ExtendedQuickSlot> ExtendQuickSlots(Queue<string> menuDescriptions)
		{
			try
			{
				int count = menuDescriptions.Count;
				int num = 0;
				List<ExtendedQuickSlot> list = new List<ExtendedQuickSlot>();
				int num2 = Enum.GetValues(typeof(QuickSlotIDs)).Cast<int>().Max() + 1;
				while (menuDescriptions.Count > 0)
				{
					int num3 = num + num2;
					int num4 = num + 1;
					string text = "QS_Instant" + num3;
					string text2 = menuDescriptions.Dequeue();
					if (string.IsNullOrEmpty(text2?.Trim()))
					{
						Logger.LogWarning(string.Format("{0}(): Empty menu description found in queue {1}. Defaulting menu message text for extra slot {2}.", "ExtendQuickSlots", "menuDescriptions", num4));
						text2 = "Ex Quick Slot {ExtraSlotNumber}".Replace("{ExtraSlotNumber}", num4.ToString());
					}
					list.Add(new ExtendedQuickSlot
					{
						QuickSlotId = num3,
						ActionName = text,
						ActionKey = "InputAction_" + text,
						ActionDescription = text2
					});
					CustomKeybindings.AddAction(text, (KeybindingsCategory)2, (ControlType)2, (InputType)1);
					Logger.LogDebug($"Adding quickslot - id: {num3}; actionName: '{text}'; description: {text2}");
					num++;
				}
				Logger.LogTrace($"RaiseSlotsChanged Event. StartId = {num2}, QuickSlotsToAdd = {list.Count}");
				return list;
			}
			catch (Exception ex)
			{
				Logger.LogException("Exception in QuickSlotExtender.ExtendQuickSlots(Queue<string> menuDescriptions). Extend failed.", ex);
				throw;
			}
		}

		public List<ExtendedQuickSlot> ExtendQuickSlots(int extendAmount, string menuDescriptionFormat)
		{
			Queue<string> queue = new Queue<string>();
			Logger.LogDebug($"Extending quickslots by {extendAmount}.");
			try
			{
				string text = menuDescriptionFormat;
				if (extendAmount < 1)
				{
					throw new ArgumentOutOfRangeException("extendAmount", string.Format("Value of {0} must be greater than 0.  Value was {1}.", "extendAmount", extendAmount));
				}
				if (string.IsNullOrEmpty(menuDescriptionFormat?.Trim()) || !menuDescriptionFormat.Contains("{ExtraSlotNumber}"))
				{
					Logger.LogWarning("ExtendQuickSlots(): '{ExtraSlotNumber}' replacer not found in menuDescriptionFormat parameter. Using default menu formatting.");
					text = "Ex Quick Slot {ExtraSlotNumber}";
				}
				for (int i = 0; i < extendAmount; i++)
				{
					queue.Enqueue(text.Replace("{ExtraSlotNumber}", (i + 1).ToString()));
				}
			}
			catch (Exception ex)
			{
				Logger.LogException("Exception in QuickSlotExtender.ExtendQuickSlots(int extendAmount, string menuDescriptionFormat). Extend failed.", ex);
				throw;
			}
			return ExtendQuickSlots(queue);
		}
	}
}
namespace ModifAmorphic.Outward.Modules.Merchants
{
	public class MerchantModule : IModifModule
	{
		private readonly Func<IModifLogger> _loggerFactory;

		private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, CustomDropTables>> _customDropTables = new ConcurrentDictionary<string, ConcurrentDictionary<string, CustomDropTables>>();

		private IModifLogger Logger => _loggerFactory();

		public HashSet<Type> PatchDependencies
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(MerchantPatches));
				return hashSet;
			}
		}

		public HashSet<Type> EventSubscriptions
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(MerchantPatches));
				return hashSet;
			}
		}

		public HashSet<Type> DepsWithMultiLogger
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(MerchantPatches));
				return hashSet;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal MerchantModule(Func<IModifLogger> loggerFactory)
		{
			_loggerFactory = loggerFactory;
			MerchantPatches.InitDropTableGameObjectAfter += AppendCustomDrops;
		}

		private void AppendCustomDrops((Merchant Merchant, Transform MerchantInventoryTablePrefab, Dropable DropableInventory) args)
		{
			Logger.LogDebug("MerchantModule::AppendCustomDrops: Looking for custom drop tables for shop '" + args.Merchant.ShopName + "'\n\tScene: " + AreaManager.Instance.CurrentArea.SceneName + "\n\tPath: " + ((Component)args.Merchant).gameObject.GetPath());
			if (!_customDropTables.TryGetValue(AreaManager.Instance.CurrentArea.SceneName, out var value) || !value.TryGetValue(((Component)args.Merchant).gameObject.GetPath(), out var value2))
			{
				return;
			}
			foreach (GuaranteedDropTable guaranteedDrop in value2.GuaranteedDrops)
			{
				GuaranteedDrop val = ((Component)args.DropableInventory).gameObject.AddComponent<GuaranteedDrop>();
				((ItemDropper)val).ItemGenatorName = guaranteedDrop.ItemGenatorName;
				val.SetItemDrops(guaranteedDrop.CustomGuaranteedDrops.ToItemDrops());
				Logger.LogDebug("MerchantModule::AppendCustomDrops:" + $" Added {guaranteedDrop.CustomGuaranteedDrops.Count} guaranteed custom drops to merchant shop '{args.Merchant.ShopName}'.");
			}
		}

		public void AddGuaranteedDrops(string sceneName, string merchantPath, IEnumerable<CustomGuaranteedDrop> guaranteedDrops, string itemGenName, string gameObjectName = "InventoryTable")
		{
			ConcurrentDictionary<string, CustomDropTables> orAdd = _customDropTables.GetOrAdd(sceneName, new ConcurrentDictionary<string, CustomDropTables>());
			CustomDropTables orAdd2 = orAdd.GetOrAdd(merchantPath, new CustomDropTables());
			orAdd2.GuaranteedDrops.Add(new GuaranteedDropTable
			{
				CustomGuaranteedDrops = guaranteedDrops.ToList(),
				ItemGenatorName = itemGenName,
				GameObjectName = gameObjectName
			});
		}
	}
	[HarmonyPatch(typeof(Merchant))]
	internal static class MerchantPatches
	{
		[MultiLogger]
		private static IModifLogger Logger { get; set; } = new NullLogger();


		public static event Action<(Merchant Merchant, Transform MerchantInventoryTablePrefab, Dropable DropableInventory)> InitDropTableGameObjectAfter;

		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPostfix]
		private static void InitDropTableGameObjectPostfix(Merchant __instance, ref Transform ___m_merchantInventoryTablePrefab, ref Dropable ___m_dropableInventory)
		{
			try
			{
				Logger.LogTrace("MerchantPatches::InitDropTableGameObjectPostfix: Raising event InitDropTableGameObjectAfter.");
				MerchantPatches.InitDropTableGameObjectAfter?.Invoke((__instance, ___m_merchantInventoryTablePrefab, ___m_dropableInventory));
			}
			catch (Exception ex)
			{
				Logger.LogException("MerchantPatches::InitDropTableGameObjectPostfix: Excepting triggering event InitDropTableGameObjectAfter.", ex);
			}
		}
	}
}
namespace ModifAmorphic.Outward.Modules.Localization
{
	public class LocalizationModule : IModifModule
	{
		private readonly string _modId;

		private readonly Func<IModifLogger> _loggerFactory;

		private IModifLogger Logger => _loggerFactory();

		public HashSet<Type> PatchDependencies
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(LocalizationManagerPatches));
				return hashSet;
			}
		}

		public HashSet<Type> EventSubscriptions
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(LocalizationManagerPatches));
				return hashSet;
			}
		}

		public HashSet<Type> DepsWithMultiLogger
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(LocalizationManagerPatches));
				hashSet.Add(typeof(LocalizationService));
				return hashSet;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal LocalizationModule(Func<IModifLogger> loggerFactory)
		{
			_loggerFactory = loggerFactory;
		}

		public void RegisterLocalization(string key, string localization)
		{
			LocalizationService.RegisterLocalization(key, localization);
		}

		public static void RegisterLocalizations(IDictionary<string, string> localizations)
		{
			LocalizationService.RegisterLocalizations(localizations);
		}
	}
}
namespace ModifAmorphic.Outward.Modules.Items
{
	internal class IconService
	{
		private readonly string _modId;

		private readonly Func<IModifLogger> _loggerFactory;

		private readonly ModifGoService _modifGoService;

		private readonly GameObject _iconsGo;

		private IModifLogger Logger => _loggerFactory();

		private Transform Icons => _iconsGo.transform;

		internal IconService(string modId, ModifGoService modifGoService, Func<IModifLogger> loggerFactory)
		{
			_modId = modId;
			_loggerFactory = loggerFactory;
			_modifGoService = modifGoService;
			_iconsGo = ((Component)UnityEngineExtensions.GetOrAddComponent<IconResources>(modifGoService.GetModResources(modId, activable: false))).gameObject;
		}

		public GameObject GetOrAddIcon(ItemDisplay itemDisplay, string iconName, string iconFilePath, bool activate = false)
		{
			string iconGameObjectName = GetIconGameObjectName(iconName);
			Transform obj = ((Component)itemDisplay).transform.Find(iconGameObjectName);
			GameObject val = ((obj != null) ? ((Component)obj).gameObject : null);
			if (Object.op_Implicit((Object)(object)val))
			{
				if (activate && !val.activeSelf)
				{
					val.SetActive(true);
				}
				return val;
			}
			GameObject orAddBaseIcon = GetOrAddBaseIcon(itemDisplay, iconName, iconFilePath);
			GameObject val2 = Object.Instantiate<GameObject>(orAddBaseIcon, ((Component)itemDisplay).transform);
			Image component = orAddBaseIcon.GetComponent<Image>();
			Image component2 = val2.GetComponent<Image>();
			Logger.LogDebug(string.Format("{0}::{1}(): Setting new image's sprite to existing {2} sprite reference from base icon.", "IconService", "GetOrAddIcon", component.sprite));
			component2.sprite = component.sprite;
			((Object)component2).name = ((Object)component).name;
			val2.DeCloneNames(recursive: true);
			if (!val2.gameObject.activeSelf && activate)
			{
				val2.gameObject.SetActive(true);
			}
			return val2;
		}

		public bool TryDeactivateIcon(ItemDisplay itemDisplay, string iconName)
		{
			string iconGameObjectName = GetIconGameObjectName(iconName);
			Transform obj = ((Component)itemDisplay).transform.Find(iconGameObjectName);
			GameObject val = ((obj != null) ? ((Component)obj).gameObject : null);
			if ((Object)(object)val == (Object)null || !val.activeSelf)
			{
				Logger.LogTrace("IconService::TryDeactivateIcon(): No existing icon GameObject '" + iconGameObjectName + "' found attached, or existing icon's GameObject " + (((val != null) ? ((Object)val).name : null) ?? " ") + "was already deactivated. No action taken.");
				return false;
			}
			val.SetActive(false);
			Logger.LogDebug("IconService::TryDeactivateIcon(): Deactivated existing icon's GameObject " + ((Object)val).name + ".");
			return true;
		}

		private string GetIconGameObjectName(string iconName)
		{
			string text = ((iconName.Length == 1) ? iconName.ToUpper() : (iconName.Substring(0, 1).ToUpper() + iconName.Substring(1)));
			if (text.StartsWith("Img"))
			{
				text = ((iconName.Length == 3) ? "" : ((text.Length > 3) ? (text.Substring(3, 1).ToUpper() + text.Substring(4)) : text.Substring(3, 1).ToUpper()));
			}
			Logger.LogTrace("IconService::GetIconGameObjectName(): img" + text + ".");
			return "img" + text;
		}

		private GameObject GetOrAddBaseIcon(ItemDisplay itemDisplay, string baseIconName, string iconPath)
		{
			string iconGameObjectName = GetIconGameObjectName(baseIconName);
			string spriteName = "icon_" + baseIconName + "Item";
			string textureName = "tex_men_" + baseIconName + "Item_v_icn";
			Transform obj = Icons.Find(iconGameObjectName);
			GameObject val = ((obj != null) ? ((Component)obj).gameObject : null);
			Logger.LogDebug(string.Format("{0}::{1}(): Tried to get base game object for icon {2}. Got {3}.", "IconService", "GetOrAddBaseIcon", iconGameObjectName, val));
			if (Object.op_Implicit((Object)(object)val))
			{
				return val;
			}
			if (!File.Exists(iconPath))
			{
				throw new FileNotFoundException("Sprite for icon " + baseIconName + " could not be loaded.", iconPath);
			}
			GameObject gameObject = ((Component)((Component)itemDisplay).transform.Find("imgEnchanted")).gameObject;
			Logger.LogDebug(string.Format("{0}::{1}(): Cloned enchanting icon gameobject {2}.", "IconService", "GetOrAddBaseIcon", gameObject));
			val = Object.Instantiate<GameObject>(gameObject, Icons);
			Image component = val.GetComponent<Image>();
			Logger.LogDebug("IconService::GetOrAddBaseIcon(): Destroying existing image " + ((Object)component).name + ".");
			Object.DestroyImmediate((Object)(object)component);
			((Object)val).name = iconGameObjectName;
			Image val2 = val.AddComponent<Image>();
			((Object)val2).name = iconGameObjectName;
			val2.LoadSpriteIcon(iconPath, spriteName, textureName);
			return val;
		}
	}
	internal class ItemPrefabService
	{
		private readonly string _modId;

		private readonly Func<IModifLogger> _loggerFactory;

		private readonly ModifGoService _modifGoService;

		private readonly ModifItemPrefabs _modifItemPrefabs;

		private readonly Func<ResourcesPrefabManager> _prefabManagerFactory;

		private readonly Dictionary<int, ItemLocalization> _itemLocalizations = new Dictionary<int, ItemLocalization>();

		private Dictionary<string, Item> _itemPrefabs;

		private IModifLogger Logger => _loggerFactory();

		public ModifItemPrefabs ModifItemPrefabs => _modifItemPrefabs;

		private ResourcesPrefabManager PrefabManager => _prefabManagerFactory();

		internal ItemPrefabService(string modId, ModifGoService modifGoService, Func<ResourcesPrefabManager> prefabManagerFactory, Func<IModifLogger> loggerFactory)
		{
			_modId = modId;
			_loggerFactory = loggerFactory;
			_modifGoService = modifGoService;
			_modifItemPrefabs = modifGoService.GetModItemPrefabs(modId);
			_prefabManagerFactory = prefabManagerFactory;
			LocalizationManagerPatches.LoadItemLocalizationAfter += RegisterItemLocalizations;
			ItemPatches.GetItemIconBefore += SetCustomItemIcon;
			ResourcesPrefabManagerPatches.TryGetItemPrefabActions.Add(delegate(int itemID, out Item item)
			{
				if (_modifItemPrefabs.Prefabs.ContainsKey(itemID))
				{
					item = _modifItemPrefabs.Prefabs[itemID];
					return true;
				}
				item = null;
				return false;
			});
		}

		private void SetCustomItemIcon(Item item)
		{
			if (item.TryGetCustomIcon(out var icon))
			{
				item.SetItemIcon(icon);
			}
		}

		public T CreatePrefab<T>(int baseItemID, int newItemID, string name, string description, bool addToResoucesPrefabManager, bool setFields) where T : Item
		{
			T basePrefab = (T)(object)PrefabManager.GetItemPrefab(baseItemID);
			return CreatePrefab(basePrefab, newItemID, name, description, addToResoucesPrefabManager, setFields);
		}

		public T CreatePrefab<T>(T basePrefab, int newItemID, string name, string description, bool addToResoucesPrefabManager, bool setFields) where T : Item
		{
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0236: Expected O, but got Unknown
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Expected O, but got Unknown
			if (string.IsNullOrEmpty(description))
			{
				description = ((Item)basePrefab).Description;
			}
			bool activeSelf = ((Component)(object)basePrefab).gameObject.activeSelf;
			((Component)(object)basePrefab).gameObject.SetActive(false);
			T val = (T)(object)((Component)(object)Object.Instantiate<T>(basePrefab, ((Component)_modifItemPrefabs).transform, false)).GetComponent<Item>();
			UnityEngineExtensions.ResetLocal(((Component)(object)val).transform, true);
			((Component)(object)basePrefab).gameObject.SetActive(activeSelf);
			if (setFields)
			{
				basePrefab.CopyFieldsTo(val);
				((Item)(object)val).SetPrivateField<Item, ItemVisual>("m_loadedVisual", null);
				if ((Object)(object)((Item)basePrefab).Stats != (Object)null)
				{
					ItemStats value = Object.Instantiate<ItemStats>(((Item)basePrefab).Stats, ((Component)(object)val).transform);
					((Item)(object)val).SetPrivateField<Item, ItemStats>("m_stats", value);
				}
				if (((Item)basePrefab).DisplayedInfos != null)
				{
					DisplayedInfos[] array = (DisplayedInfos[])(object)new DisplayedInfos[((Item)basePrefab).DisplayedInfos.Length];
					Array.Copy(((Item)basePrefab).DisplayedInfos, array, array.Length);
					((Item)(object)val).SetPrivateField<Item, DisplayedInfos[]>("m_displayedInfos", array);
					((Item)(object)val).SetPrivateField<Item, bool>("m_displayedInfoInitialzed", value: false);
				}
				object obj = basePrefab;
				Equipment val2 = (Equipment)((obj is Equipment) ? obj : null);
				if (val2 != null)
				{
					object obj2 = val;
					Equipment val3 = (Equipment)((obj2 is Equipment) ? obj2 : null);
					if (val3 != null)
					{
						ProcessEquipmentFields(val2, val3);
					}
				}
				object obj3 = val;
				Weapon val4 = (Weapon)((obj3 is Weapon) ? obj3 : null);
				if (val4 != null)
				{
					ProcessWeaponFields(val4);
				}
				object obj4 = basePrefab;
				Armor val5 = (Armor)((obj4 is Armor) ? obj4 : null);
				if (val5 != null)
				{
					object obj5 = val;
					Armor val6 = (Armor)((obj5 is Armor) ? obj5 : null);
					if (val6 != null)
					{
						ProcessArmorFields(val5, val6);
					}
				}
			}
			((Item)val).SetDLC(((Item)basePrefab).DLCID);
			((Item)val).ItemID = newItemID;
			((Item)val).IsPrefab = true;
			((Item)(object)val).SetNames(name).SetDescription(description);
			ItemLocalization value2 = new ItemLocalization(name, description);
			_itemLocalizations.AddOrUpdate(((Item)val).ItemID, new ItemLocalization(name, description));
			Dictionary<int, ItemLocalization> privateField = LocalizationManager.Instance.GetPrivateField<LocalizationManager, Dictionary<int, ItemLocalization>>("m_itemLocalization");
			privateField.AddOrUpdate(((Item)val).ItemID, value2);
			if (addToResoucesPrefabManager)
			{
				GetItemPrefabs().AddOrUpdate(((Item)val).ItemIDString, (Item)(object)val);
			}
			else
			{
				_modifItemPrefabs.Add((Item)(object)val);
			}
			return val;
		}

		private void ProcessWeaponFields(Weapon weapon)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			weapon.SetPrivateField<Weapon, DamageList>("m_enchantmentDamageBonus", new DamageList());
			weapon.SetPrivateField<Weapon, DamageList>("m_baseDamage", null);
			weapon.SetPrivateField<Weapon, DamageList>("m_activeBaseDamage", null);
			weapon.SetPrivateField<Weapon, List<Character>>("m_alreadyHitChars", new List<Character>());
			weapon.SetPrivateField<Weapon, DamageList>("m_lastDealtDamages", new DamageList());
			weapon.SetPrivateField<Weapon, DictionaryExt<string, ImbueStack>>("m_imbueStack", new DictionaryExt<string, ImbueStack>());
			weapon.SetPrivateField<Weapon, List<Tag>>("tmpattackTags", new List<Tag>());
			weapon.SetPrivateField<Weapon, DamageList>("baseDamage", null);
		}

		private void ProcessArmorFields(Armor sourceArmor, Armor targetArmor)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			ArmorBaseData privateField = sourceArmor.GetPrivateField<Armor, ArmorBaseData>("m_baseData");
			if (privateField != null)
			{
				ArmorBaseData value = new ArmorBaseData
				{
					Class = privateField.Class,
					ColdProtection = privateField.ColdProtection,
					DamageReduction = privateField.DamageReduction?.ToList(),
					DamageResistance = privateField.DamageResistance?.ToList()
				};
				targetArmor.SetPrivateField<Armor, ArmorBaseData>("m_baseData", value);
			}
		}

		private void ProcessEquipmentFields(Equipment source, Equipment target)
		{
			target.AssociatedEquipment = null;
			target.SetPrivateField<Equipment, List<Enchantment>>("m_activeEnchantments", source.GetPrivateField<Equipment, List<Enchantment>>("m_activeEnchantments")?.ToList());
			target.SetPrivateField<Equipment, List<Effect>>("m_appliedAffectStats", source.GetPrivateField<Equipment, List<Effect>>("m_appliedAffectStats")?.ToList());
			target.SetPrivateField<Equipment, List<int>>("m_enchantmentIDs", source.GetPrivateField<Equipment, List<int>>("m_enchantmentIDs")?.ToList());
			target.SetPrivateField<Equipment, SummonedEquipment>("m_summonedEquipment", null);
		}

		public Dictionary<string, Item> GetItemPrefabs()
		{
			if (_itemPrefabs == null)
			{
				FieldInfo field = typeof(ResourcesPrefabManager).GetField("ITEM_PREFABS", BindingFlags.Static | BindingFlags.NonPublic);
				_itemPrefabs = field.GetValue(null) as Dictionary<string, Item>;
			}
			return _itemPrefabs;
		}

		private void RegisterItemLocalizations(ref Dictionary<int, ItemLocalization> targetLocalizations)
		{
			foreach (KeyValuePair<int, ItemLocalization> itemLocalization in _itemLocalizations)
			{
				targetLocalizations.AddOrUpdate(itemLocalization.Key, itemLocalization.Value);
			}
		}
	}
	public class ItemVisualizer : IModifModule
	{
		private readonly Func<IModifLogger> _loggerFactory;

		private readonly Func<ResourcesPrefabManager> _prefabManagerFactory;

		private readonly Func<ItemManager> _itemManagerFactory;

		private readonly IconService _iconService;

		private readonly ConcurrentDictionary<string, int> _itemVisuals = new ConcurrentDictionary<string, int>();

		private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, string>> _itemsIcons = new ConcurrentDictionary<string, ConcurrentDictionary<string, string>>();

		private readonly HashSet<string> _displayIcons = new HashSet<string>();

		private IModifLogger Logger => _loggerFactory();

		private ResourcesPrefabManager PrefabManager => _prefabManagerFactory();

		private ItemManager ItemManager => _itemManagerFactory();

		public HashSet<Type> PatchDependencies
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(ItemManagerPatches));
				hashSet.Add(typeof(ItemDisplayPatches));
				return hashSet;
			}
		}

		public HashSet<Type> EventSubscriptions => new HashSet<Type>();

		public HashSet<Type> DepsWithMultiLogger
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(ItemManagerPatches));
				hashSet.Add(typeof(ItemDisplayPatches));
				return hashSet;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal ItemVisualizer(Func<ResourcesPrefabManager> prefabManagerFactory, Func<ItemManager> itemManagerFactory, IconService iconService, Func<IModifLogger> loggerFactory)
		{
			_loggerFactory = loggerFactory;
			_prefabManagerFactory = prefabManagerFactory;
			_itemManagerFactory = itemManagerFactory;
			_iconService = iconService;
			ItemManagerPatches.GetVisualsByItemAfter += SetVisualsByItem;
			ItemManagerPatches.GetSpecialVisualsByItemAfter += SetSpecialVisualsByItem;
			ItemDisplayPatches.RefreshEnchantedIconAfter += ToggleCustomIcons;
		}

		public void RegisterItemVisual(int visualItemID, string targetItemUID)
		{
			Logger.LogDebug(string.Format("{0}::{1}(): Registering target UID '{2}' to use ItemID {3} visuals.", "ItemVisualizer", "RegisterItemVisual", targetItemUID, visualItemID));
			_itemVisuals.TryAdd(targetItemUID, visualItemID);
		}

		public void UnregisterItemVisual(string targetItemUID)
		{
			Logger.LogDebug("ItemVisualizer::RegisterItemVisual(): Unregistering target UID '" + targetItemUID + "'.");
			_itemVisuals.TryRemove(targetItemUID, out var _);
		}

		public bool IsItemVisualRegistered(string itemUID)
		{
			return _itemVisuals.ContainsKey(itemUID);
		}

		public void RegisterAdditionalIcon(string itemUID, string iconName, string iconPath)
		{
			Logger.LogDebug("ItemVisualizer::RegisterItemVisual(): Registering new Icon " + iconName + " to Item UID '" + itemUID + "'. Icon file path: " + iconPath + ".");
			ConcurrentDictionary<string, string> orAdd = _itemsIcons.GetOrAdd(itemUID, new ConcurrentDictionary<string, string>());
			orAdd.TryAdd(iconName, iconPath);
			if (!_displayIcons.Contains(iconName))
			{
				_displayIcons.Add(iconName);
			}
		}

		public void UnregisterAdditionalIcon(string itemUID, string iconName)
		{
			Logger.LogDebug("ItemVisualizer::RegisterItemVisual(): Unregistering Icon " + iconName + " from Item UID '" + itemUID + "'.");
			if (_itemsIcons.TryGetValue(itemUID, out var value))
			{
				value.TryRemove(iconName, out var _);
				if (value.Count == 0)
				{
					_itemsIcons.TryRemove(itemUID, out var _);
				}
			}
		}

		public bool IsAdditionalIconRegistered(string itemUID, string iconName)
		{
			ConcurrentDictionary<string, string> value;
			return _itemsIcons.TryGetValue(itemUID, out value) && value.ContainsKey(iconName);
		}

		private void SetVisualsByItem(Item item, ref ItemVisual visual)
		{
			if (TryGetVisualsByItem(item, out var visual2))
			{
				visual = visual2;
			}
		}

		private bool TryGetVisualsByItem(Item item, out ItemVisual visual)
		{
			visual = null;
			if (!_itemVisuals.TryGetValue(item.UID, out var value))
			{
				Logger.LogTrace(string.Format("{0}::{1}(): No custom ItemVisual mapping found for {2} - {3} ({4}).", "ItemVisualizer", "TryGetVisualsByItem", item.ItemID, item.DisplayName, item.UID));
				return false;
			}
			item.SetPrivateField<Item, ItemVisual>("m_loadedVisual", null);
			visual = ItemManager.GetVisuals(value);
			IModifLogger logger = Logger;
			string text = string.Format("{0}::{1}(): ItemVisual mapping found for {2} - {3} ({4}). Replaced ", "ItemVisualizer", "TryGetVisualsByItem", item.ItemID, item.DisplayName, item.UID);
			object arg = value;
			ItemVisual obj = visual;
			logger.LogDebug(text + $"visuals with ItemID {arg}'s ItemVisual - {((obj != null) ? ((Object)obj).name : null)}");
			Item itemPrefab = PrefabManager.GetItemPrefab(value);
			ToggleModelOnEnchant component = ((Component)itemPrefab).GetComponent<ToggleModelOnEnchant>();
			if ((Object)(object)component != (Object)null && (Object)(object)((Component)item).GetComponent<ToggleModelOnEnchant>() == (Object)null)
			{
				ToggleModelOnEnchant val = ((Component)item).gameObject.AddComponent<ToggleModelOnEnchant>();
				val.ModelName = component.ModelName;
				((Object)val).name = ((Object)item).name;
				((Component)val).gameObject.SetActive(true);
			}
			ConfigureVisualToggles(item, value);
			return (Object)(object)visual != (Object)null;
		}

		private void SetSpecialVisualsByItem(Item item, ref ItemVisual visual)
		{
			if (TryGetSpecialVisualsByItem(item, out var visual2))
			{
				visual = visual2;
			}
		}

		private bool TryGetSpecialVisualsByItem(Item item, out ItemVisual visual)
		{
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			visual = null;
			if (!_itemVisuals.TryGetValue(item.UID, out var value))
			{
				Logger.LogTrace(string.Format("{0}::{1}(): No custom ItemVisual mapping found for {2} - {3} ({4}).", "ItemVisualizer", "SetSpecialVisualsByItem", item.ItemID, item.DisplayName, item.UID));
				return false;
			}
			item.SetPrivateField<Item, ItemVisual>("m_loadedVisual", null);
			Item itemPrefab = PrefabManager.GetItemPrefab(value);
			if (itemPrefab.HasSpecialVisualPrefab)
			{
				Item val = PrefabManager.GenerateItem(value.ToString());
				val.SetHolderUID(UID.op_Implicit(Global.GenerateUID()));
				if ((Object)(object)((EffectSynchronizer)item).OwnerCharacter != (Object)null)
				{
					val.SetPrivateField<Item, Character>("m_ownerCharacter", ((EffectSynchronizer)item).OwnerCharacter);
				}
				Logger.LogDebug(string.Format("{0}::{1}(): HasSpecialVisualPrefab --> Generated temporary Item and set it's owner to {2} to retrieve ItemVisual. ", "ItemVisualizer", "SetSpecialVisualsByItem", ((EffectSynchronizer)val).OwnerCharacter) + $" Generated Item: {val.ItemID} - {val.DisplayName} ({val.UID})");
				visual = ItemManager.GetSpecialVisuals(val);
				Object.Destroy((Object)(object)((Component)val).gameObject);
				IModifLogger logger = Logger;
				string text = string.Format("{0}::{1}(): HasSpecialVisualPrefab --> ItemVisual mapping found for {2} - {3} ({4}). Replaced ", "ItemVisualizer", "SetSpecialVisualsByItem", item.ItemID, item.DisplayName, item.UID);
				object arg = value;
				ItemVisual obj = visual;
				logger.LogDebug(text + $"visuals with ItemID {arg}'s ItemVisual - {((obj != null) ? ((Object)obj).name : null)}");
			}
			else
			{
				visual = ItemManager.GetVisuals(value);
				IModifLogger logger2 = Logger;
				string text2 = string.Format("{0}::{1}(): ItemVisual mapping found for {2} - {3} ({4}). Replaced ", "ItemVisualizer", "SetSpecialVisualsByItem", item.ItemID, item.DisplayName, item.UID);
				object arg2 = value;
				ItemVisual obj2 = visual;
				logger2.LogDebug(text2 + $"visuals with ItemID {arg2}'s ItemVisual - {((obj2 != null) ? ((Object)obj2).name : null)}");
			}
			if ((Object)(object)visual != (Object)null)
			{
				visual.SetLinkedItem(item);
			}
			ConfigureVisualToggles(item, value);
			return (Object)(object)visual != (Object)null;
		}

		private void ConfigureVisualToggles(Item item, int visualItemID)
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			Item itemPrefab = PrefabManager.GetItemPrefab(visualItemID);
			ToggleModelOnEnchant component = ((Component)itemPrefab).GetComponent<ToggleModelOnEnchant>();
			if ((Object)(object)component != (Object)null && (Object)(object)((Component)item).GetComponent<ToggleModelOnEnchant>() == (Object)null)
			{
				ToggleModelOnEnchant val = ((Component)item).gameObject.AddComponent<ToggleModelOnEnchant>();
				val.ModelName = component.ModelName;
				((Object)val).name = ((Object)item).name;
				((Component)val).gameObject.SetActive(true);
			}
			SwapColor component2 = ((Component)itemPrefab).GetComponent<SwapColor>();
			if ((Object)(object)component2 != (Object)null && (Object)(object)((Component)item).GetComponent<SwapColor>() == (Object)null)
			{
				SwapColor val2 = ((Component)item).gameObject.AddComponent<SwapColor>();
				val2.DefaultColor = component2.DefaultColor;
				val2.Palette = component2.Palette;
				((Object)val2).name = ((Object)item).name;
				((Component)val2).gameObject.SetActive(true);
			}
		}

		private void ToggleCustomIcons(ItemDisplay itemDisplay, Item item)
		{
			HashSet<string> hashSet = new HashSet<string>();
			Logger.LogTrace(string.Format("{0}::{1}(): Setting custom icons for Item {2} - {3} ({4}) current ItemDisplay {5}.", "ItemVisualizer", "ToggleCustomIcons", item?.ItemID, (item != null) ? item.DisplayName : null, (item != null) ? item.UID : null, ((Object)itemDisplay).name));
			if ((Object)(object)item != (Object)null && !string.IsNullOrEmpty(item.UID) && _itemsIcons.TryGetValue(item.UID, out var value))
			{
				foreach (KeyValuePair<string, string> item2 in value)
				{
					_iconService.GetOrAddIcon(itemDisplay, item2.Key, item2.Value, activate: true);
					hashSet.Add(item2.Key);
					Logger.LogDebug("ItemVisualizer::ToggleCustomIcons(): Added icon " + item2.Key + " to ItemDisplay " + ((Object)itemDisplay).name + ".");
				}
			}
			foreach (string displayIcon in _displayIcons)
			{
				if (!hashSet.Contains(displayIcon) && _iconService.TryDeactivateIcon(itemDisplay, displayIcon))
				{
					Logger.LogTrace("ItemVisualizer::ToggleCustomIcons(): Deactivated icon " + displayIcon + " for ItemDisplay " + ((Object)itemDisplay).name + ".");
				}
			}
		}

		private bool TryUnregisterItemVisual(Item containedItem, out (string UID, int VisualItemID) visualMap)
		{
			if (_itemVisuals.TryRemove(containedItem.UID, out var value))
			{
				visualMap = (containedItem.UID, value);
				containedItem.SetPrivateField<Item, ItemVisual>("m_loadedVisual", null);
				Logger.LogDebug(string.Format("{0}::{1}(): Unregistered target UID '{2}' from ItemID {3} visuals.\n", "ItemVisualizer", "RegisterItemVisual", containedItem.UID, value) + $"\tm_loadedVisual: {containedItem.GetLoadedVisual()}");
				Logger.LogDebug("ItemVisualizer::RegisterItemVisual(): Visuals: \n" + $"\tLoadedVisual: {containedItem.LoadedVisual}" + $"\tCurrentVisual: {containedItem.CurrentVisual}");
				return true;
			}
			visualMap = default((string, int));
			return false;
		}

		private bool PositionVisualsOverride(VisualSlot visualSlot, ref Item item)
		{
			if (string.IsNullOrEmpty(item.UID) || (!_itemVisuals.TryGetValue(item.UID, out var value) && !item.DisplayName.Contains("Virgin")))
			{
				return false;
			}
			Logger.LogDebug(string.Format("{0}::{1}(): Starting PositionVisuals processing for {2} - {3} ({4}) and ", "ItemVisualizer", "PositionVisualsOverride", item.ItemID, item.DisplayName, item.UID) + $"visualItemID {value}.");
			VisualSlotWrapper visualSlotWrapper = VisualSlotWrapper.Wrap(visualSlot);
			if (!Application.isPlaying)
			{
				visualSlotWrapper.m_currentItem = item;
				Logger.LogDebug(string.Format("{0}::{1}(): Application.isPlaying == false.  m_currentItem set to item {2} - {3} ({4}).", "ItemVisualizer", "PositionVisualsOverride", item.ItemID, item.DisplayName, item.UID));
			}
			else
			{
				Logger.LogDebug(string.Format("{0}::{1}(): Application.isPlaying == true for item: {2} - {3} ({4}).", "ItemVisualizer", "PositionVisualsOverride", item.ItemID, item.DisplayName, item.UID));
				if ((Object)(object)visualSlotWrapper.m_editorCurrentVisuals != (Object)null)
				{
					visualSlotWrapper.m_currentVisual = visualSlotWrapper.m_editorCurrentVisuals;
					Logger.LogDebug(string.Format("{0}::{1}(): m_editorCurrentVisuals != null. Set m_currentVisual to m_editorCurrentVisuals {2} for item: {3} - {4} ({5}).", "ItemVisualizer", "PositionVisualsOverride", visualSlotWrapper.m_editorCurrentVisuals, item.ItemID, item.DisplayName, item.UID));
				}
				if ((Object)(object)item == (Object)(object)visualSlotWrapper.m_currentItem)
				{
					if (!item.HasSpecialVisualPrefab)
					{
						Logger.LogDebug(string.Format("{0}::{1}(): !item.HasSpecialVisualPrefab. Calling item.LinkVisuals({2}, false). item: {3} - {4} ({5}).", "ItemVisualizer", "PositionVisualsOverride", visualSlotWrapper.m_currentVisual, item.ItemID, item.DisplayName, item.UID));
						item.LinkVisuals(visualSlotWrapper.m_currentVisual, false);
					}
					Logger.LogDebug(string.Format("{0}::{1}(): item == m_currentItem.  Calling PositionVisuals() for item: {2} - {3} ({4}).", "ItemVisualizer", "PositionVisualsOverride", item.ItemID, item.DisplayName, item.UID));
					visualSlotWrapper.PositionVisuals();
					return true;
				}
				if ((Object)(object)visualSlotWrapper.m_currentItem != (Object)null)
				{
					Logger.LogDebug(string.Format("{0}::{1}(): vs.m_currentItem != null. m_currentItem is [{2} - {3} ({4})]. Calling PutBackVisuals(). item: {5} - {6} ({7}).", "ItemVisualizer", "PositionVisualsOverride", visualSlotWrapper.m_currentItem.ItemID, visualSlotWrapper.m_currentItem.DisplayName, visualSlotWrapper.m_currentItem.UID, item.ItemID, item.DisplayName, item.UID));
					visualSlot.PutBackVisuals();
				}
				IModifLogger logger = Logger;
				object[] obj = new object[8]
				{
					"ItemVisualizer",
					"PositionVisualsOverride",
					visualSlotWrapper.m_currentItem?.ItemID,
					null,
					null,
					null,
					null,
					null
				};
				Item currentItem = visualSlotWrapper.m_currentItem;
				obj[3] = ((currentItem != null) ? currentItem.DisplayName : null);
				Item currentItem2 = visualSlotWrapper.m_currentItem;
				obj[4] = ((currentItem2 != null) ? currentItem2.UID : null);
				obj[5] = item.ItemID;
				obj[6] = item.DisplayName;
				obj[7] = item.UID;
				logger.LogDebug(string.Format("{0}::{1}(): m_currentItem [{2} - {3} ({4})] being set to param item [{5} - {6} ({7})].", obj));
				visualSlotWrapper.m_currentItem = item;
			}
			if ((Object)(object)visualSlotWrapper.m_currentVisual == (Object)null)
			{
				Logger.LogDebug(string.Format("{0}::{1}(): m_currentVisual == null. item: [{2} - {3} ({4})].", "ItemVisualizer", "PositionVisualsOverride", item.ItemID, item.DisplayName, item.UID));
				if (!item.HasSpecialVisualPrefab)
				{
					Logger.LogDebug(string.Format("{0}::{1}(): !item.HasSpecialVisualPrefab (No Special). m_currentVisual [{2}] set to item.LoadedVisual [{3}]. ", "ItemVisualizer", "PositionVisualsOverride", visualSlotWrapper.m_currentVisual, item.LoadedVisual) + $"m_editorCurrentVisuals [{visualSlotWrapper.m_editorCurrentVisuals}] set to m_currentVisual [{visualSlotWrapper.m_currentVisual}]. " + $"item: [{item.ItemID} - {item.DisplayName} ({item.UID})].");
					visualSlotWrapper.m_currentVisual = item.LoadedVisual;
					visualSlotWrapper.m_editorCurrentVisuals = visualSlotWrapper.m_currentVisual;
				}
				else
				{
					Logger.LogDebug(string.Format("{0}::{1}(): item.HasSpecialVisualPrefab == true. m_currentVisual [{2}]. m_editorCurrentVisuals [{3}]. ", "ItemVisualizer", "PositionVisualsOverride", visualSlotWrapper.m_currentVisual, visualSlotWrapper.m_editorCurrentVisuals) + $"item: [{item.ItemID} - {item.DisplayName} ({item.UID})].");
					visualSlotWrapper.m_currentVisual = ItemManager.GetSpecialVisuals(item);
					visualSlotWrapper.m_editorCurrentVisuals = visualSlotWrapper.m_currentVisual;
					Logger.LogDebug(string.Format("{0}::{1}(): ItemManager.GetSpecialVisuals({2} - {3} ({4})). m_currentVisual now [{5}] and m_editorCurrentVisuals [{6}].", "ItemVisualizer", "PositionVisualsOverride", item.ItemID, item.DisplayName, item.UID, visualSlotWrapper.m_currentVisual, visualSlotWrapper.m_currentVisual));
					if (Object.op_Implicit((Object)(object)visualSlotWrapper.m_currentVisual))
					{
						Logger.LogDebug(string.Format("{0}::{1}(): m_currentVisual.Show(). m_currentVisual [{2}]. item: [{3} - {4} ({5})].", "ItemVisualizer", "PositionVisualsOverride", visualSlotWrapper.m_currentVisual, item.ItemID, item.DisplayName, item.UID));
						visualSlotWrapper.m_currentVisual.Show();
					}
					if (item is Equipment)
					{
						Logger.LogDebug(string.Format("{0}::{1}(): item is Equipment. IsEnchanted == {2}. Calling (item as Equipment).SetSpecialVisuals({3}) item: [{4} - {5} ({6})].", "ItemVisualizer", "PositionVisualsOverride", item.IsEnchanted, visualSlotWrapper.m_currentVisual, item.ItemID, item.DisplayName, item.UID));
						Item obj2 = item;
						((Equipment)((obj2 is Equipment) ? obj2 : null)).SetSpecialVisuals(visualSlotWrapper.m_currentVisual);
					}
				}
			}
			if (Application.isPlaying)
			{
				Logger.LogDebug(string.Format("{0}::{1}(): Application.isPlaying == true. Setting m_editorCurrentVisuals [{2}] to  m_currentVisual [{3}].item: [{4} - {5} ({6})].", "ItemVisualizer", "PositionVisualsOverride", visualSlotWrapper.m_editorCurrentVisuals, visualSlotWrapper.m_currentVisual, item.ItemID, item.DisplayName, item.UID));
				visualSlotWrapper.m_editorCurrentVisuals = visualSlotWrapper.m_currentVisual;
			}
			else if ((Object)(object)visualSlotWrapper.m_currentItem != (Object)null)
			{
				Logger.LogDebug(string.Format("{0}::{1}(): m_currentItem != null. Setting m_editorCurrentVisuals [{2}] to  m_currentVisual [{3}].  item: [{4} - {5} ({6})].", "ItemVisualizer", "PositionVisualsOverride", visualSlotWrapper.m_editorCurrentVisuals, visualSlotWrapper.m_currentVisual, item.ItemID, item.DisplayName, item.UID));
				visualSlotWrapper.m_editorCurrentVisuals = visualSlotWrapper.m_currentVisual;
			}
			Logger.LogDebug(string.Format("{0}::{1}(): Calling PositionVisuals() then returning true.  item: [{2} - {3} ({4})].", "ItemVisualizer", "PositionVisualsOverride", item.ItemID, item.DisplayName, item.UID));
			visualSlotWrapper.PositionVisuals();
			return true;
		}
	}
	public class PreFabricator : IModifModule
	{
		private readonly string _modId;

		private readonly Func<IModifLogger> _loggerFactory;

		private readonly ItemPrefabService _itemPrefabService;

		private IModifLogger Logger => _loggerFactory();

		public ModifItemPrefabs ModifItemPrefabs => _itemPrefabService.ModifItemPrefabs;

		public HashSet<Type> PatchDependencies
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(LocalizationManagerPatches));
				hashSet.Add(typeof(ItemPatches));
				hashSet.Add(typeof(ResourcesPrefabManagerPatches));
				return hashSet;
			}
		}

		public HashSet<Type> EventSubscriptions
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(LocalizationManagerPatches));
				hashSet.Add(typeof(ItemPatches));
				hashSet.Add(typeof(ResourcesPrefabManagerPatches));
				return hashSet;
			}
		}

		public HashSet<Type> DepsWithMultiLogger
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(LocalizationManagerPatches));
				hashSet.Add(typeof(ItemPatches));
				hashSet.Add(typeof(ResourcesPrefabManagerPatches));
				return hashSet;
			}
		}

		internal PreFabricator(string modId, ItemPrefabService itemPrefabService, Func<IModifLogger> loggerFactory)
		{
			_modId = modId;
			_loggerFactory = loggerFactory;
			_itemPrefabService = itemPrefabService;
		}

		public T CreatePrefab<T>(int baseItemID, int newItemID, string name, string description, bool addToResourcesPrefabManager, bool setFields = false) where T : Item
		{
			return _itemPrefabService.CreatePrefab<T>(baseItemID, newItemID, name, description, addToResourcesPrefabManager, setFields);
		}

		public T CreatePrefab<T>(T basePrefab, int newItemID, string name, string description, bool addToResourcesPrefabManager, bool setFields = false) where T : Item
		{
			return _itemPrefabService.CreatePrefab(basePrefab, newItemID, name, description, addToResourcesPrefabManager, setFields);
		}

		public T GetPrefab<T>(int itemID) where T : Item
		{
			if (ModifItemPrefabs.Prefabs.TryGetValue(itemID, out var value))
			{
				T val = (T)(object)((value is T) ? value : null);
				if (val != null)
				{
					return val;
				}
			}
			return default(T);
		}

		public bool TryGetPrefab<T>(int itemID, out T prefab) where T : Item
		{
			prefab = GetPrefab<T>(itemID);
			return (Object)(object)prefab != (Object)null;
		}

		public void RemovePrefab(int itemID)
		{
			ModifItemPrefabs.Remove(itemID);
		}
	}
}
namespace ModifAmorphic.Outward.Modules.Items.Patches
{
	[HarmonyPatch(typeof(ItemDisplay))]
	internal static class ItemDisplayPatches
	{
		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private static Action<ItemDisplay, Item> m_RefreshEnchantedIconAfter;

		[MultiLogger]
		private static IModifLogger Logger { get; set; } = new NullLogger();


		public static event Action<ItemDisplay, Item> RefreshEnchantedIconAfter
		{
			[CompilerGenerated]
			add
			{
				Action<ItemDisplay, Item> val = ItemDisplayPatches.m_RefreshEnchantedIconAfter;
				Action<ItemDisplay, Item> val2;
				do
				{
					val2 = val;
					Action<ItemDisplay, Item> value2 = (Action<ItemDisplay, Item>)(object)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref ItemDisplayPatches.m_RefreshEnchantedIconAfter, value2, val2);
				}
				while (val != val2);
			}
			[CompilerGenerated]
			remove
			{
				Action<ItemDisplay, Item> val = ItemDisplayPatches.m_RefreshEnchantedIconAfter;
				Action<ItemDisplay, Item> val2;
				do
				{
					val2 = val;
					Action<ItemDisplay, Item> value2 = (Action<ItemDisplay, Item>)(object)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value);
					val = Interlocked.CompareExchange(ref ItemDisplayPatches.m_RefreshEnchantedIconAfter, value2, val2);
				}
				while (val != val2);
			}
		}

		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPostfix]
		public static void RefreshEnchantedIconPostfix(ItemDisplay __instance, Item ___m_refItem)
		{
			try
			{
				Logger.LogTrace(string.Format("{0}::{1}(): Invoked for ItemDisplay {2} and Item {3} - {4} ({5}). Invoking {6}().", "ItemDisplayPatches", "RefreshEnchantedIconPostfix", ((Object)__instance).name, ___m_refItem?.ItemID, (___m_refItem != null) ? ___m_refItem.DisplayName : null, (___m_refItem != null) ? ___m_refItem.UID : null, "RefreshEnchantedIconAfter"));
				ItemDisplayPatches.RefreshEnchantedIconAfter?.Invoke(__instance, ___m_refItem);
			}
			catch (Exception ex)
			{
				Logger.LogException("ItemDisplayPatches::RefreshEnchantedIconPostfix(): Exception Invoking RefreshEnchantedIconAfter().", ex);
			}
		}
	}
	[HarmonyPatch(typeof(ItemManager))]
	public static class ItemManagerPatches
	{
		public delegate void GetVisualsByItem(Item input, ref ItemVisual itemVisual);

		[MultiLogger]
		private static IModifLogger Logger { get; set; } = new NullLogger();


		public static event GetVisualsByItem GetSpecialVisualsByItemAfter;

		public static event GetVisualsByItem GetVisualsByItemAfter;

		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPostfix]
		[HarmonyPatch(new Type[] { typeof(Item) })]
		public static void GetSpecialVisualsPostfix(ref Item _item, ref ItemVisual __result)
		{
			try
			{
				if (!((Object)(object)_item == (Object)null) && !string.IsNullOrEmpty(_item.UID))
				{
					Logger.LogTrace(string.Format("{0}::{1}(): Invoked on Item {2} - {3} ({4}). Invoking {5}().", "ItemManagerPatches", "GetSpecialVisualsPostfix", _item.ItemID, _item.DisplayName, _item.UID, "GetSpecialVisualsByItemAfter"));
					ItemManagerPatches.GetSpecialVisualsByItemAfter?.Invoke(_item, ref __result);
				}
			}
			catch (Exception ex)
			{
				Logger.LogException("ItemManagerPatches::GetSpecialVisualsPostfix(): Exception Invoking GetSpecialVisualsByItemAfter().", ex);
			}
		}

		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPostfix]
		[HarmonyPatch(new Type[] { typeof(Item) })]
		private static void GetVisualsByItemPostfix(ref Item _item, ref ItemVisual __result)
		{
			try
			{
				if (!((Object)(object)_item == (Object)null) && !string.IsNullOrEmpty(_item.UID))
				{
					Logger.LogTrace(string.Format("{0}::{1}(): Invoked on Item {2} - {3} ({4}). Invoking {5}()", "ItemManagerPatches", "GetVisualsByItemPostfix", _item.ItemID, _item.DisplayName, _item.UID, "GetVisualsByItemPostfix"));
					ItemManagerPatches.GetVisualsByItemAfter?.Invoke(_item, ref __result);
				}
			}
			catch (Exception ex)
			{
				Logger.LogException("ItemManagerPatches::GetVisualsByItemPostfix(): Exception Invoking GetVisualsByItemPostfix().", ex);
			}
		}

		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPrefix]
		[HarmonyPatch(new Type[]
		{
			typeof(int),
			typeof(ItemVisual)
		})]
		public static void PutBackVisualItemIDFix(ref int _itemID, ref ItemVisual _visuals)
		{
			try
			{
				if (!((Object)(object)_visuals == (Object)null))
				{
					int itemIDFromName = _visuals.GetItemIDFromName();
					Logger.LogTrace(string.Format("{0}::{1}(): Invoked for ItemID {2} and visual ItemVisual: {3}. GetItemIDFromName(): {4}.", "ItemManagerPatches", "PutBackVisualItemIDFix", _itemID, _visuals, itemIDFromName));
					if (itemIDFromName != _itemID)
					{
						_itemID = itemIDFromName;
						Logger.LogTrace(string.Format("{0}::{1}(): ItemID set to {2}.", "ItemManagerPatches", "PutBackVisualItemIDFix", _itemID));
					}
				}
			}
			catch (Exception ex)
			{
				Logger.LogException(string.Format("{0}::{1}(): Exception Fixing ItemID for _itemID {2}, _visuals {3}.", "ItemManagerPatches", "PutBackVisualItemIDFix", _itemID, _visuals), ex);
			}
		}
	}
	[HarmonyPatch(typeof(Item))]
	public static class ItemPatches
	{
		[MultiLogger]
		private static IModifLogger Logger { get; set; } = new NullLogger();


		public static event Action<Item> GetItemIconBefore;

		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPrefix]
		private static void ItemIconPrefix(Item __instance)
		{
			try
			{
				ItemPatches.GetItemIconBefore?.Invoke(__instance);
			}
			catch (Exception ex)
			{
				Logger.LogException("ItemPatches::ItemIconPrefix(): Exception Invoking GetItemIconBefore().", ex);
			}
		}
	}
	[HarmonyPatch(typeof(ResourcesPrefabManager))]
	internal static class ResourcesPrefabManagerPatches
	{
		public delegate bool TryGetItemPrefabDelegate(int itemID, out Item itemPrefab);

		public static List<TryGetItemPrefabDelegate> TryGetItemPrefabActions = new List<TryGetItemPrefabDelegate>();

		[MultiLogger]
		private static IModifLogger Logger { get; set; } = new NullLogger();


		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPostfix]
		[HarmonyPatch(new Type[] { typeof(int) })]
		private static void GetItemPrefabByInt(int _itemID, ref Item __result)
		{
			try
			{
				if (!((Object)(object)__result != (Object)null))
				{
					Logger.LogTrace("ResourcesPrefabManagerPatches::GetItemPrefabByInt: Invoking TryGetItemPrefabActions");
					GetItemPrefab(_itemID, ref __result);
				}
			}
			catch (Exception ex)
			{
				Logger.LogException("ResourcesPrefabManagerPatches::GetItemPrefabByInt: Exception Invoking TryGetItemPrefabActions.", ex);
			}
		}

		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPostfix]
		[HarmonyPatch(new Type[] { typeof(string) })]
		private static void GetItemPrefabByString(string _itemIDString, ref Item __result)
		{
			try
			{
				if (!((Object)(object)__result != (Object)null) && int.TryParse(_itemIDString, out var result))
				{
					Logger.LogTrace("ResourcesPrefabManagerPatches::GetItemPrefabByString: Invoking TryGetItemPrefabActions");
					GetItemPrefab(result, ref __result);
				}
			}
			catch (Exception ex)
			{
				Logger.LogException("ResourcesPrefabManagerPatches::GetItemPrefabByString: Exception Invoking TryGetItemPrefabActions.", ex);
			}
		}

		private static void GetItemPrefab(int itemID, ref Item item)
		{
			for (int i = 0; i < TryGetItemPrefabActions.Count; i++)
			{
				if (TryGetItemPrefabActions[0](itemID, out var itemPrefab))
				{
					item = itemPrefab;
					break;
				}
			}
		}
	}
}
namespace ModifAmorphic.Outward.Modules.Items.Models
{
	internal class VisualSlotWrapper
	{
		private readonly VisualSlot _visualSlot;

		public Item m_currentItem
		{
			get
			{
				return _visualSlot.GetPrivateField<VisualSlot, Item>("m_currentItem");
			}
			set
			{
				_visualSlot.SetPrivateField<VisualSlot, Item>("m_currentItem", value);
			}
		}

		public ItemVisual m_editorCurrentVisuals
		{
			get
			{
				return _visualSlot.GetPrivateField<VisualSlot, ItemVisual>("m_editorCurrentVisuals");
			}
			set
			{
				_visualSlot.SetPrivateField<VisualSlot, ItemVisual>("m_editorCurrentVisuals", value);
			}
		}

		public ItemVisual m_currentVisual
		{
			get
			{
				return _visualSlot.GetPrivateField<VisualSlot, ItemVisual>("m_currentVisual");
			}
			set
			{
				_visualSlot.SetPrivateField<VisualSlot, ItemVisual>("m_currentVisual", value);
			}
		}

		public Action PositionVisuals => delegate
		{
			_visualSlot.InvokePrivateMethod<VisualSlot>("PositionVisuals", Array.Empty<object>());
		};

		private VisualSlotWrapper(VisualSlot visualSlot)
		{
			_visualSlot = visualSlot;
		}

		public static VisualSlotWrapper Wrap(VisualSlot visualSlot)
		{
			return new VisualSlotWrapper(visualSlot);
		}
	}
}
namespace ModifAmorphic.Outward.Modules.Crafting
{
	public class CustomCraftingModule : IModifModule
	{
		private readonly Func<IModifLogger> _loggerFactory;

		private readonly CraftingMenuUIService _menuUiService;

		private readonly RecipeDisplayService _recipeDisplayService;

		private readonly CustomRecipeService _customRecipeService;

		private readonly CustomCraftingService _craftingService;

		private readonly List<CraftingMenuMetadata> _registeredMenus = new List<CraftingMenuMetadata>();

		private readonly ConcurrentDictionary<int, List<CraftingMenuMetadata>> _characterMenus = new ConcurrentDictionary<int, List<CraftingMenuMetadata>>();

		private readonly ConcurrentDictionary<Type, CraftingMenuMetadata> _craftingMenus = new ConcurrentDictionary<Type, CraftingMenuMetadata>();

		private readonly ConcurrentDictionary<Type, Dictionary<string, RecipeMetadata>> _customRecipes = new ConcurrentDictionary<Type, Dictionary<string, RecipeMetadata>>();

		private readonly ConcurrentDictionary<Type, CraftingType> _craftingStationTypes = new ConcurrentDictionary<Type, CraftingType>();

		public readonly CraftingMenuEvents CraftingMenuEvents;

		private IModifLogger Logger => _loggerFactory();

		internal RecipeDisplayService RecipeDisplayService => _recipeDisplayService;

		internal CustomRecipeService CustomRecipeService => _customRecipeService;

		internal CustomCraftingService CustomCraftingService => _craftingService;

		public HashSet<Type> PatchDependencies
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(CharacterUIPatches));
				hashSet.Add(typeof(CraftingMenuPatches));
				hashSet.Add(typeof(CompatibleIngredientPatches));
				hashSet.Add(typeof(LocalizationManagerPatches));
				return hashSet;
			}
		}

		public HashSet<Type> EventSubscriptions
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(CharacterUIPatches));
				hashSet.Add(typeof(CraftingMenuPatches));
				hashSet.Add(typeof(LocalizationManagerPatches));
				return hashSet;
			}
		}

		public HashSet<Type> DepsWithMultiLogger
		{
			get
			{
				HashSet<Type> hashSet = new HashSet<Type>();
				hashSet.Add(typeof(CharacterUIPatches));
				hashSet.Add(typeof(CraftingMenuPatches));
				hashSet.Add(typeof(CompatibleIngredientPatches));
				hashSet.Add(typeof(LocalizationManagerPatches));
				return hashSet;
			}
		}

		internal CustomCraftingModule(CraftingMenuUIService menuUIService, RecipeDisplayService recipeDisplayService, CustomRecipeService customRecipeService, CustomCraftingService craftingService, CraftingMenuEvents craftingMenuEvents, Func<IModifLogger> loggerFactory)
		{
			_menuUiService = menuUIService;
			_recipeDisplayService = recipeDisplayService;
			_customRecipeService = customRecipeService;
			_craftingService = craftingService;
			CraftingMenuEvents = craftingMenuEvents;
			_loggerFactory = loggerFactory;
			CharacterUIPatches.AwakeBefore += CharacterUIPatches_AwakeBefore;
			CharacterUIPatches.RegisterMenuAfter += CharacterUIPatches_RegisterMenuAfter;
			CraftingMenuPatches.AwakeInitAfter += CraftingMenuPatches_AwakeInitAfter;
			recipeDisplayService.MenuHiding += delegate(CustomCraftingMenu menu)
			{
				CraftingMenuEvents.InvokeMenuHiding(menu);
			};
		}

		private void CraftingMenuPatches_AwakeInitAfter(CraftingMenu craftingMenu)
		{
			if (!(craftingMenu is CustomCraftingMenu))
			{
				AddCustomCraftingMenus(craftingMenu);
			}
		}

		private void CharacterUIPatches_AwakeBefore(CharacterUI characterUI)
		{
			AddCraftingTabAndFooter(characterUI);
		}

		private void CharacterUIPatches_RegisterMenuAfter(CharacterUI characterUI, CustomCraftingMenu craftingMenu)
		{
			Type type = ((object)craftingMenu).GetType();
			int rewiredID = characterUI.RewiredID;
			if (_craftingMenus.TryGetValue(type, out var value))
			{
				MenuTab[] privateField = characterUI.GetPrivateField<CharacterUI, MenuTab[]>("m_menuTabs");
				CraftingMenuMetadata meta = value.Clone();
				meta.MenuType = type;
				meta.MenuPanel = craftingMenu;
				meta.MenuDisplay = ((Component)craftingMenu).gameObject;
				meta.MenuTab = ((Component)privateField.First((MenuTab t) => t.TabName == meta.TabName).Tab).gameObject;
				meta.MenuFooter = _menuUiService.GetFooter(characterUI, meta.FooterName);
				List<CraftingMenuMetadata> orAdd = _characterMenus.GetOrAdd(rewiredID, new List<CraftingMenuMetadata>());
				orAdd.Add(meta);
				CraftingMenuEvents?.InvokeMenuLoading(craftingMenu);
			}
		}

		public CraftingType RegisterCraftingMenu<T>(string menuDisplayName, MenuIcons menuIcons = null) where T : CustomCraftingMenu
		{
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			if (_craftingMenus.ContainsKey(typeof(T)))
			{
				throw new ArgumentException(string.Format("{0} of type {1} already exists. ", "CustomCraftingMenu", typeof(T)) + "Only one instance of a type derived from CustomCraftingMenu can be added.", "T");
			}
			menuIcons?.TrySetIconNames(menuDisplayName);
			_craftingMenus.TryAdd(typeof(T), new CraftingMenuMetadata
			{
				MenuType = typeof(T),
				TabButtonName = "btn" + typeof(T).Name,
				TabName = "PlayerMenu_Tab_" + typeof(T).Name,
				TabDisplayName = menuDisplayName,
				MenuName = typeof(T).Name,
				MenuIcons = menuIcons,
				FooterName = typeof(T).Name + "Footer"
			});
			_registeredMenus.Add(_craftingMenus[typeof(T)]);
			_craftingStationTypes.TryAdd(typeof(T), (CraftingType)_menuUiService.AddIngredientTag());
			TryAddRecipes();
			return _craftingStationTypes[typeof(T)];
		}

		public void RegisterRecipe<T>(Recipe recipe) where T : CustomCraftingMenu
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			ValidateRecipe(recipe);
			Logger.LogTrace("CustomCraftingModule:RegisterRecipe:: Recipe " + ((Object)recipe).name + " is valid.  Registering recipe.");
			Dictionary<string, RecipeMetadata> orAdd = _customRecipes.GetOrAdd(typeof(T), new Dictionary<string, RecipeMetadata>());
			UID uID = recipe.UID;
			if (orAdd.ContainsKey(((object)(UID)(ref uID)).ToString()))
			{
				throw new ArgumentException($"A Recipe with UID '{recipe.UID}' is already registered for crafting station type {typeof(T).Name}.", "recipe");
			}
			uID = recipe.UID;
			orAdd.Add(((object)(UID)(ref uID)).ToString(), new RecipeMetadata
			{
				CraftingStationType = typeof(T),
				Recipe = recipe
			});
			TryAddRecipes();
		}

		public List<Recipe> GetRegisteredRecipes<T>()
		{
			Dictionary<string, RecipeMetadata> value;
			return _customRecipes.TryGetValue(typeof(T), out value) ? value.Values.Select((RecipeMetadata r) => r.Recipe).ToList() : new List<Recipe>();
		}

		public void RegisterCustomCrafter<T>(ICustomCrafter crafter) where T : CustomCraftingMenu
		{
			_craftingService.AddOrUpdateCrafter<T>(crafter);
		}

		public void RegisterMenuIngredientFilters<T>(MenuIngredientFilters filter) where T : CustomCraftingMenu
		{
			_craftingService.AddOrUpdateIngredientFilter<T>(filter);
		}

		public void UnregisterMenuIngredientFilters<T>() where T : CustomCraftingMenu
		{
			_craftingService.TryRemoveIngredientFilter<T>();
		}

		public bool TryGetRegisteredIngredientFilters<T>(out MenuIngredientFilters filter) where T : CustomCraftingMenu
		{
			return _craftingService.TryGetIngredientFilter<T>(out filter);
		}

		public void RegisterRecipeVisibiltyController<T>(IRecipeVisibiltyController visibiltyController) where T : CustomCraftingMenu
		{
			_recipeDisplayService.AddOrUpdateRecipeVisibiltyController<T>(visibiltyController);
		}

		public void UnregisterRecipeVisibiltyController<T>() where T : CustomCraftingMenu
		{
			_recipeDisplayService.TryRemoveRecipeVisibiltyController<T>();
		}

		public void RegisterCompatibleIngredientMatcher<T>(ICompatibleIngredientMatcher matcher) where T : CustomCraftingMenu
		{
			_craftingService.AddOrUpdateCompatibleIngredientMatcher<T>(matcher);
		}

		public void RegisterConsumedItemSelector<T>(IConsumedItemSelector itemSelector) where T : CustomCraftingMenu
		{
			_craftingService.AddOrUpdateConsumedItemSelector<T>(itemSelector);
		}

		public void UnregisterConsumedItemSelector<T>() where T : CustomCraftingMenu
		{
			_craftingService.TryRemoveConsumedItemSelector<T>();
		}

		public void RegisterRecipeSelectorDisplayConfig<T>(RecipeSelectorDisplayConfig config) where T : CustomCraftingMenu
		{
			_recipeDisplayService.AddUpdateDisplayConfig<T>(config);
		}

		public bool TryGetRegisteredRecipeDisplayConfig<T>(out RecipeSelectorDisplayConfig config) where T : CustomCraftingMenu
		{
			return _recipeDisplayService.TryGetDisplayConfig<T>(out config);
		}

		public void RegisterStaticIngredients<T>(IEnumerable<StaticIngredient> ingredients) where T : CustomCraftingMenu
		{
			_recipeDisplayService.AddOrUpdateStaticIngredients<T>(ingredients);
		}

		public void UnregisterStaticIngredients<T>() where T : CustomCraftingMenu
		{
			_recipeDisplayService.TryRemoveStaticIngredients<T>();
		}

		public void EnableCraftingMenu<T>() where T : CustomCraftingMenu
		{
			if (!_craftingMenus.TryGetValue(typeof(T), out var _))
			{
				throw new ArgumentException($"CustomCraftingMenu {typeof(T)} is not a registered menu type. Menus " + "must be registered using RegisterCraftingMenu<T> and loaded before they can be enabled or disabled.", "T");
			}
			IEnumerable<Character> enumerable = SplitScreenManager.Instance.LocalPlayers.Select((SplitPlayer p) => p.AssignedCharacter);
			foreach (Character item in enumerable)
			{
				int playerID = item.OwnerPlayerSys.PlayerID;
				if (_characterMenus.TryGetValue(playerID, out var value2))
				{
					CraftingMenuMetadata meta = value2.FirstOrDefault((CraftingMenuMetadata m) => m.MenuType == typeof(T));
					_menuUiService.EnableMenuTab(item.CharacterUI, meta);
				}
			}
		}

		public void DisableCraftingMenu<T>() where T : CustomCraftingMenu
		{
			if (!_craftingMenus.TryGetValue(typeof(T), out var _))
			{
				throw new ArgumentException($"CustomCraftingMenu {typeof(T)} is not a registered menu type. Menus " + "must be registered using RegisterCraftingMenu<T> and loaded before they can be enabled or disabled.", "T");
			}
			IEnumerable<Character> enumerable = SplitScreenManager.Instance.LocalPlayers.Select((SplitPlayer p) => p.AssignedCharacter);
			foreach (Character item in enumerable)
			{
				int playerID = item.OwnerPlayerSys.PlayerID;
				if (_characterMenus.TryGetValue(playerID, out var value2))
				{
					CraftingMenuMetadata meta = value2.FirstOrDefault((CraftingMenuMetadata m) => m.MenuType == typeof(T));
					_menuUiService.DisableMenuTab(item.CharacterUI, meta);
				}
			}
		}

		private void ValidateRecipe(Recipe recipe)
		{
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Invalid comparison between Unknown and I4
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			if (recipe.IsFullySetup)
			{
				return;
			}
			string text = $"Recipe '{recipe.RecipeID} - {recipe.Name}' IsFullySetup is false.";
			if (recipe.Results == null || recipe.Results.Length == 0 || recipe.Results[0] == null)
			{
				throw new ArgumentException(text + " The recipe's Results are not configured properly. Either the Results are empty or null.", "recipe");
			}
			if ((Object)(object)recipe.Results[0].RefItem == (Object)null)
			{
				throw new ArgumentException($"{text} Recipe's Results[0].RefItem is null. Ensure ItemID '{recipe.Results[0].ItemID}' of the result has a valid Prefab.", "recipe");
			}
			if (recipe.Ingredients == null || recipe.Ingredients.Length == 0)
			{
				throw new ArgumentException(text + " Recipe's Ingredients are null or empty. Reci

Newtonsoft.Json.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Linq.JsonPath;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Newtonsoft")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © James Newton-King 2008")]
[assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")]
[assembly: AssemblyFileVersion("13.0.3.27908")]
[assembly: AssemblyInformationalVersion("13.0.3+0a2e291c0d9c0c7675d445703e51750363a549ef")]
[assembly: AssemblyProduct("Json.NET")]
[assembly: AssemblyTitle("Json.NET .NET Standard 2.0")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/JamesNK/Newtonsoft.Json")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("13.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
}
namespace Newtonsoft.Json
{
	public enum ConstructorHandling
	{
		Default,
		AllowNonPublicDefaultConstructor
	}
	public enum DateFormatHandling
	{
		IsoDateFormat,
		MicrosoftDateFormat
	}
	public enum DateParseHandling
	{
		None,
		DateTime,
		DateTimeOffset
	}
	public enum DateTimeZoneHandling
	{
		Local,
		Utc,
		Unspecified,
		RoundtripKind
	}
	public class DefaultJsonNameTable : JsonNameTable
	{
		private class Entry
		{
			internal readonly string Value;

			internal readonly int HashCode;

			internal Entry Next;

			internal Entry(string value, int hashCode, Entry next)
			{
				Value = value;
				HashCode = hashCode;
				Next = next;
			}
		}

		private static readonly int HashCodeRandomizer;

		private int _count;

		private Entry[] _entries;

		private int _mask = 31;

		static DefaultJsonNameTable()
		{
			HashCodeRandomizer = Environment.TickCount;
		}

		public DefaultJsonNameTable()
		{
			_entries = new Entry[_mask + 1];
		}

		public override string? Get(char[] key, int start, int length)
		{
			if (length == 0)
			{
				return string.Empty;
			}
			int num = length + HashCodeRandomizer;
			num += (num << 7) ^ key[start];
			int num2 = start + length;
			for (int i = start + 1; i < num2; i++)
			{
				num += (num << 7) ^ key[i];
			}
			num -= num >> 17;
			num -= num >> 11;
			num -= num >> 5;
			int num3 = Volatile.Read(ref _mask);
			int num4 = num & num3;
			for (Entry entry = _entries[num4]; entry != null; entry = entry.Next)
			{
				if (entry.HashCode == num && TextEquals(entry.Value, key, start, length))
				{
					return entry.Value;
				}
			}
			return null;
		}

		public string Add(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			int length = key.Length;
			if (length == 0)
			{
				return string.Empty;
			}
			int num = length + HashCodeRandomizer;
			for (int i = 0; i < key.Length; i++)
			{
				num += (num << 7) ^ key[i];
			}
			num -= num >> 17;
			num -= num >> 11;
			num -= num >> 5;
			for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next)
			{
				if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal))
				{
					return entry.Value;
				}
			}
			return AddEntry(key, num);
		}

		private string AddEntry(string str, int hashCode)
		{
			int num = hashCode & _mask;
			Entry entry = new Entry(str, hashCode, _entries[num]);
			_entries[num] = entry;
			if (_count++ == _mask)
			{
				Grow();
			}
			return entry.Value;
		}

		private void Grow()
		{
			Entry[] entries = _entries;
			int num = _mask * 2 + 1;
			Entry[] array = new Entry[num + 1];
			for (int i = 0; i < entries.Length; i++)
			{
				Entry entry = entries[i];
				while (entry != null)
				{
					int num2 = entry.HashCode & num;
					Entry next = entry.Next;
					entry.Next = array[num2];
					array[num2] = entry;
					entry = next;
				}
			}
			_entries = array;
			Volatile.Write(ref _mask, num);
		}

		private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length)
		{
			if (str1.Length != str2Length)
			{
				return false;
			}
			for (int i = 0; i < str1.Length; i++)
			{
				if (str1[i] != str2[str2Start + i])
				{
					return false;
				}
			}
			return true;
		}
	}
	[Flags]
	public enum DefaultValueHandling
	{
		Include = 0,
		Ignore = 1,
		Populate = 2,
		IgnoreAndPopulate = 3
	}
	public enum FloatFormatHandling
	{
		String,
		Symbol,
		DefaultValue
	}
	public enum FloatParseHandling
	{
		Double,
		Decimal
	}
	public enum Formatting
	{
		None,
		Indented
	}
	public interface IArrayPool<T>
	{
		T[] Rent(int minimumLength);

		void Return(T[]? array);
	}
	public interface IJsonLineInfo
	{
		int LineNumber { get; }

		int LinePosition { get; }

		bool HasLineInfo();
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonArrayAttribute : JsonContainerAttribute
	{
		private bool _allowNullItems;

		public bool AllowNullItems
		{
			get
			{
				return _allowNullItems;
			}
			set
			{
				_allowNullItems = value;
			}
		}

		public JsonArrayAttribute()
		{
		}

		public JsonArrayAttribute(bool allowNullItems)
		{
			_allowNullItems = allowNullItems;
		}

		public JsonArrayAttribute(string id)
			: base(id)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)]
	public sealed class JsonConstructorAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public abstract class JsonContainerAttribute : Attribute
	{
		internal bool? _isReference;

		internal bool? _itemIsReference;

		internal ReferenceLoopHandling? _itemReferenceLoopHandling;

		internal TypeNameHandling? _itemTypeNameHandling;

		private Type? _namingStrategyType;

		private object[]? _namingStrategyParameters;

		public string? Id { get; set; }

		public string? Title { get; set; }

		public string? Description { get; set; }

		public Type? ItemConverterType { get; set; }

		public object[]? ItemConverterParameters { get; set; }

		public Type? NamingStrategyType
		{
			get
			{
				return _namingStrategyType;
			}
			set
			{
				_namingStrategyType = value;
				NamingStrategyInstance = null;
			}
		}

		public object[]? NamingStrategyParameters
		{
			get
			{
				return _namingStrategyParameters;
			}
			set
			{
				_namingStrategyParameters = value;
				NamingStrategyInstance = null;
			}
		}

		internal NamingStrategy? NamingStrategyInstance { get; set; }

		public bool IsReference
		{
			get
			{
				return _isReference.GetValueOrDefault();
			}
			set
			{
				_isReference = value;
			}
		}

		public bool ItemIsReference
		{
			get
			{
				return _itemIsReference.GetValueOrDefault();
			}
			set
			{
				_itemIsReference = value;
			}
		}

		public ReferenceLoopHandling ItemReferenceLoopHandling
		{
			get
			{
				return _itemReferenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_itemReferenceLoopHandling = value;
			}
		}

		public TypeNameHandling ItemTypeNameHandling
		{
			get
			{
				return _itemTypeNameHandling.GetValueOrDefault();
			}
			set
			{
				_itemTypeNameHandling = value;
			}
		}

		protected JsonContainerAttribute()
		{
		}

		protected JsonContainerAttribute(string id)
		{
			Id = id;
		}
	}
	public static class JsonConvert
	{
		public static readonly string True = "true";

		public static readonly string False = "false";

		public static readonly string Null = "null";

		public static readonly string Undefined = "undefined";

		public static readonly string PositiveInfinity = "Infinity";

		public static readonly string NegativeInfinity = "-Infinity";

		public static readonly string NaN = "NaN";

		public static Func<JsonSerializerSettings>? DefaultSettings { get; set; }

		public static string ToString(DateTime value)
		{
			return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
		}

		public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
		{
			DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
			using StringWriter stringWriter = StringUtils.CreateStringWriter(64);
			stringWriter.Write('"');
			DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture);
			stringWriter.Write('"');
			return stringWriter.ToString();
		}

		public static string ToString(DateTimeOffset value)
		{
			return ToString(value, DateFormatHandling.IsoDateFormat);
		}

		public static string ToString(DateTimeOffset value, DateFormatHandling format)
		{
			using StringWriter stringWriter = StringUtils.CreateStringWriter(64);
			stringWriter.Write('"');
			DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture);
			stringWriter.Write('"');
			return stringWriter.ToString();
		}

		public static string ToString(bool value)
		{
			if (!value)
			{
				return False;
			}
			return True;
		}

		public static string ToString(char value)
		{
			return ToString(char.ToString(value));
		}

		public static string ToString(Enum value)
		{
			return value.ToString("D");
		}

		public static string ToString(int value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(short value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(ushort value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(uint value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(long value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		private static string ToStringInternal(BigInteger value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(ulong value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(float value)
		{
			return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
		}

		internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
		}

		private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value)))
			{
				return text;
			}
			if (floatFormatHandling == FloatFormatHandling.DefaultValue)
			{
				if (nullable)
				{
					return Null;
				}
				return "0.0";
			}
			return quoteChar + text + quoteChar;
		}

		public static string ToString(double value)
		{
			return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
		}

		internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
		}

		private static string EnsureDecimalPlace(double value, string text)
		{
			if (double.IsNaN(value) || double.IsInfinity(value) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1)
			{
				return text;
			}
			return text + ".0";
		}

		private static string EnsureDecimalPlace(string text)
		{
			if (StringUtils.IndexOf(text, '.') != -1)
			{
				return text;
			}
			return text + ".0";
		}

		public static string ToString(byte value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(sbyte value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(decimal value)
		{
			return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
		}

		public static string ToString(Guid value)
		{
			return ToString(value, '"');
		}

		internal static string ToString(Guid value, char quoteChar)
		{
			string text = value.ToString("D", CultureInfo.InvariantCulture);
			string text2 = quoteChar.ToString(CultureInfo.InvariantCulture);
			return text2 + text + text2;
		}

		public static string ToString(TimeSpan value)
		{
			return ToString(value, '"');
		}

		internal static string ToString(TimeSpan value, char quoteChar)
		{
			return ToString(value.ToString(), quoteChar);
		}

		public static string ToString(Uri? value)
		{
			if (value == null)
			{
				return Null;
			}
			return ToString(value, '"');
		}

		internal static string ToString(Uri value, char quoteChar)
		{
			return ToString(value.OriginalString, quoteChar);
		}

		public static string ToString(string? value)
		{
			return ToString(value, '"');
		}

		public static string ToString(string? value, char delimiter)
		{
			return ToString(value, delimiter, StringEscapeHandling.Default);
		}

		public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling)
		{
			if (delimiter != '"' && delimiter != '\'')
			{
				throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter");
			}
			return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling);
		}

		public static string ToString(object? value)
		{
			if (value == null)
			{
				return Null;
			}
			return ConvertUtils.GetTypeCode(value.GetType()) switch
			{
				PrimitiveTypeCode.String => ToString((string)value), 
				PrimitiveTypeCode.Char => ToString((char)value), 
				PrimitiveTypeCode.Boolean => ToString((bool)value), 
				PrimitiveTypeCode.SByte => ToString((sbyte)value), 
				PrimitiveTypeCode.Int16 => ToString((short)value), 
				PrimitiveTypeCode.UInt16 => ToString((ushort)value), 
				PrimitiveTypeCode.Int32 => ToString((int)value), 
				PrimitiveTypeCode.Byte => ToString((byte)value), 
				PrimitiveTypeCode.UInt32 => ToString((uint)value), 
				PrimitiveTypeCode.Int64 => ToString((long)value), 
				PrimitiveTypeCode.UInt64 => ToString((ulong)value), 
				PrimitiveTypeCode.Single => ToString((float)value), 
				PrimitiveTypeCode.Double => ToString((double)value), 
				PrimitiveTypeCode.DateTime => ToString((DateTime)value), 
				PrimitiveTypeCode.Decimal => ToString((decimal)value), 
				PrimitiveTypeCode.DBNull => Null, 
				PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), 
				PrimitiveTypeCode.Guid => ToString((Guid)value), 
				PrimitiveTypeCode.Uri => ToString((Uri)value), 
				PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), 
				PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), 
				_ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), 
			};
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value)
		{
			return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Formatting formatting)
		{
			return SerializeObject(value, formatting, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return SerializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return SerializeObject(value, null, formatting, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, JsonSerializerSettings? settings)
		{
			return SerializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			return SerializeObjectInternal(value, type, jsonSerializer);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings)
		{
			return SerializeObject(value, null, formatting, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			jsonSerializer.Formatting = formatting;
			return SerializeObjectInternal(value, type, jsonSerializer);
		}

		private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer)
		{
			StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture);
			using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter))
			{
				jsonTextWriter.Formatting = jsonSerializer.Formatting;
				jsonSerializer.Serialize(jsonTextWriter, value, type);
			}
			return stringWriter.ToString();
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value)
		{
			return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value, JsonSerializerSettings settings)
		{
			return DeserializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value, Type type)
		{
			return DeserializeObject(value, type, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static T? DeserializeObject<T>(string value)
		{
			return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
		{
			return DeserializeObject<T>(value);
		}

		[DebuggerStepThrough]
		public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
		{
			return DeserializeObject<T>(value, settings);
		}

		[DebuggerStepThrough]
		public static T? DeserializeObject<T>(string value, params JsonConverter[] converters)
		{
			return (T)DeserializeObject(value, typeof(T), converters);
		}

		[DebuggerStepThrough]
		public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings)
		{
			return (T)DeserializeObject(value, typeof(T), settings);
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return DeserializeObject(value, type, settings);
		}

		public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings)
		{
			ValidationUtils.ArgumentNotNull(value, "value");
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			if (!jsonSerializer.IsCheckAdditionalContentSet())
			{
				jsonSerializer.CheckAdditionalContent = true;
			}
			using JsonTextReader reader = new JsonTextReader(new StringReader(value));
			return jsonSerializer.Deserialize(reader, type);
		}

		[DebuggerStepThrough]
		public static void PopulateObject(string value, object target)
		{
			PopulateObject(value, target, null);
		}

		public static void PopulateObject(string value, object target, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			using JsonReader jsonReader = new JsonTextReader(new StringReader(value));
			jsonSerializer.Populate(jsonReader, target);
			if (settings == null || !settings.CheckAdditionalContent)
			{
				return;
			}
			while (jsonReader.Read())
			{
				if (jsonReader.TokenType != JsonToken.Comment)
				{
					throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object.");
				}
			}
		}

		public static string SerializeXmlNode(XmlNode? node)
		{
			return SerializeXmlNode(node, Formatting.None);
		}

		public static string SerializeXmlNode(XmlNode? node, Formatting formatting)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter
			{
				OmitRootObject = omitRootObject
			};
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		public static XmlDocument? DeserializeXmlNode(string value)
		{
			return DeserializeXmlNode(value, null);
		}

		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName)
		{
			return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false);
		}

		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
		{
			return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false);
		}

		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName;
			xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute;
			xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters;
			return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter);
		}

		public static string SerializeXNode(XObject? node)
		{
			return SerializeXNode(node, Formatting.None);
		}

		public static string SerializeXNode(XObject? node, Formatting formatting)
		{
			return SerializeXNode(node, formatting, omitRootObject: false);
		}

		public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter
			{
				OmitRootObject = omitRootObject
			};
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		public static XDocument? DeserializeXNode(string value)
		{
			return DeserializeXNode(value, null);
		}

		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName)
		{
			return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false);
		}

		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
		{
			return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false);
		}

		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName;
			xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute;
			xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters;
			return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter);
		}
	}
	public abstract class JsonConverter
	{
		public virtual bool CanRead => true;

		public virtual bool CanWrite => true;

		public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer);

		public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer);

		public abstract bool CanConvert(Type objectType);
	}
	public abstract class JsonConverter<T> : JsonConverter
	{
		public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
		{
			if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T))))
			{
				throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
			}
			WriteJson(writer, (T)value, serializer);
		}

		public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer);

		public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
		{
			bool flag = existingValue == null;
			if (!flag && !(existingValue is T))
			{
				throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
			}
			return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer);
		}

		public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer);

		public sealed override bool CanConvert(Type objectType)
		{
			return typeof(T).IsAssignableFrom(objectType);
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class JsonConverterAttribute : Attribute
	{
		private readonly Type _converterType;

		public Type ConverterType => _converterType;

		public object[]? ConverterParameters { get; }

		public JsonConverterAttribute(Type converterType)
		{
			if (converterType == null)
			{
				throw new ArgumentNullException("converterType");
			}
			_converterType = converterType;
		}

		public JsonConverterAttribute(Type converterType, params object[] converterParameters)
			: this(converterType)
		{
			ConverterParameters = converterParameters;
		}
	}
	public class JsonConverterCollection : Collection<JsonConverter>
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonDictionaryAttribute : JsonContainerAttribute
	{
		public JsonDictionaryAttribute()
		{
		}

		public JsonDictionaryAttribute(string id)
			: base(id)
		{
		}
	}
	[Serializable]
	public class JsonException : Exception
	{
		public JsonException()
		{
		}

		public JsonException(string message)
			: base(message)
		{
		}

		public JsonException(string message, Exception? innerException)
			: base(message, innerException)
		{
		}

		public JsonException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			return new JsonException(message);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class JsonExtensionDataAttribute : Attribute
	{
		public bool WriteData { get; set; }

		public bool ReadData { get; set; }

		public JsonExtensionDataAttribute()
		{
			WriteData = true;
			ReadData = true;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class JsonIgnoreAttribute : Attribute
	{
	}
	public abstract class JsonNameTable
	{
		public abstract string? Get(char[] key, int start, int length);
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonObjectAttribute : JsonContainerAttribute
	{
		private MemberSerialization _memberSerialization;

		internal MissingMemberHandling? _missingMemberHandling;

		internal Required? _itemRequired;

		internal NullValueHandling? _itemNullValueHandling;

		public MemberSerialization MemberSerialization
		{
			get
			{
				return _memberSerialization;
			}
			set
			{
				_memberSerialization = value;
			}
		}

		public MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling.GetValueOrDefault();
			}
			set
			{
				_missingMemberHandling = value;
			}
		}

		public NullValueHandling ItemNullValueHandling
		{
			get
			{
				return _itemNullValueHandling.GetValueOrDefault();
			}
			set
			{
				_itemNullValueHandling = value;
			}
		}

		public Required ItemRequired
		{
			get
			{
				return _itemRequired.GetValueOrDefault();
			}
			set
			{
				_itemRequired = value;
			}
		}

		public JsonObjectAttribute()
		{
		}

		public JsonObjectAttribute(MemberSerialization memberSerialization)
		{
			MemberSerialization = memberSerialization;
		}

		public JsonObjectAttribute(string id)
			: base(id)
		{
		}
	}
	internal enum JsonContainerType
	{
		None,
		Object,
		Array,
		Constructor
	}
	internal struct JsonPosition
	{
		private static readonly char[] SpecialCharacters = new char[18]
		{
			'.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t',
			'\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029'
		};

		internal JsonContainerType Type;

		internal int Position;

		internal string? PropertyName;

		internal bool HasIndex;

		public JsonPosition(JsonContainerType type)
		{
			Type = type;
			HasIndex = TypeHasIndex(type);
			Position = -1;
			PropertyName = null;
		}

		internal int CalculateLength()
		{
			switch (Type)
			{
			case JsonContainerType.Object:
				return PropertyName.Length + 5;
			case JsonContainerType.Array:
			case JsonContainerType.Constructor:
				return MathUtils.IntLength((ulong)Position) + 2;
			default:
				throw new ArgumentOutOfRangeException("Type");
			}
		}

		internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer)
		{
			switch (Type)
			{
			case JsonContainerType.Object:
			{
				string propertyName = PropertyName;
				if (propertyName.IndexOfAny(SpecialCharacters) != -1)
				{
					sb.Append("['");
					if (writer == null)
					{
						writer = new StringWriter(sb);
					}
					JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer);
					sb.Append("']");
				}
				else
				{
					if (sb.Length > 0)
					{
						sb.Append('.');
					}
					sb.Append(propertyName);
				}
				break;
			}
			case JsonContainerType.Array:
			case JsonContainerType.Constructor:
				sb.Append('[');
				sb.Append(Position);
				sb.Append(']');
				break;
			}
		}

		internal static bool TypeHasIndex(JsonContainerType type)
		{
			if (type != JsonContainerType.Array)
			{
				return type == JsonContainerType.Constructor;
			}
			return true;
		}

		internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition)
		{
			int num = 0;
			if (positions != null)
			{
				for (int i = 0; i < positions.Count; i++)
				{
					num += positions[i].CalculateLength();
				}
			}
			if (currentPosition.HasValue)
			{
				num += currentPosition.GetValueOrDefault().CalculateLength();
			}
			StringBuilder stringBuilder = new StringBuilder(num);
			StringWriter writer = null;
			char[] buffer = null;
			if (positions != null)
			{
				foreach (JsonPosition position in positions)
				{
					position.WriteTo(stringBuilder, ref writer, ref buffer);
				}
			}
			currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer);
			return stringBuilder.ToString();
		}

		internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message)
		{
			if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal))
			{
				message = message.Trim();
				if (!StringUtils.EndsWith(message, '.'))
				{
					message += ".";
				}
				message += " ";
			}
			message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path);
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition);
			}
			message += ".";
			return message;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class JsonPropertyAttribute : Attribute
	{
		internal NullValueHandling? _nullValueHandling;

		internal DefaultValueHandling? _defaultValueHandling;

		internal ReferenceLoopHandling? _referenceLoopHandling;

		internal ObjectCreationHandling? _objectCreationHandling;

		internal TypeNameHandling? _typeNameHandling;

		internal bool? _isReference;

		internal int? _order;

		internal Required? _required;

		internal bool? _itemIsReference;

		internal ReferenceLoopHandling? _itemReferenceLoopHandling;

		internal TypeNameHandling? _itemTypeNameHandling;

		public Type? ItemConverterType { get; set; }

		public object[]? ItemConverterParameters { get; set; }

		public Type? NamingStrategyType { get; set; }

		public object[]? NamingStrategyParameters { get; set; }

		public NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling.GetValueOrDefault();
			}
			set
			{
				_nullValueHandling = value;
			}
		}

		public DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling.GetValueOrDefault();
			}
			set
			{
				_defaultValueHandling = value;
			}
		}

		public ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_referenceLoopHandling = value;
			}
		}

		public ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling.GetValueOrDefault();
			}
			set
			{
				_objectCreationHandling = value;
			}
		}

		public TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling.GetValueOrDefault();
			}
			set
			{
				_typeNameHandling = value;
			}
		}

		public bool IsReference
		{
			get
			{
				return _isReference.GetValueOrDefault();
			}
			set
			{
				_isReference = value;
			}
		}

		public int Order
		{
			get
			{
				return _order.GetValueOrDefault();
			}
			set
			{
				_order = value;
			}
		}

		public Required Required
		{
			get
			{
				return _required.GetValueOrDefault();
			}
			set
			{
				_required = value;
			}
		}

		public string? PropertyName { get; set; }

		public ReferenceLoopHandling ItemReferenceLoopHandling
		{
			get
			{
				return _itemReferenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_itemReferenceLoopHandling = value;
			}
		}

		public TypeNameHandling ItemTypeNameHandling
		{
			get
			{
				return _itemTypeNameHandling.GetValueOrDefault();
			}
			set
			{
				_itemTypeNameHandling = value;
			}
		}

		public bool ItemIsReference
		{
			get
			{
				return _itemIsReference.GetValueOrDefault();
			}
			set
			{
				_itemIsReference = value;
			}
		}

		public JsonPropertyAttribute()
		{
		}

		public JsonPropertyAttribute(string propertyName)
		{
			PropertyName = propertyName;
		}
	}
	public abstract class JsonReader : IDisposable
	{
		protected internal enum State
		{
			Start,
			Complete,
			Property,
			ObjectStart,
			Object,
			ArrayStart,
			Array,
			Closed,
			PostValue,
			ConstructorStart,
			Constructor,
			Error,
			Finished
		}

		private JsonToken _tokenType;

		private object? _value;

		internal char _quoteChar;

		internal State _currentState;

		private JsonPosition _currentPosition;

		private CultureInfo? _culture;

		private DateTimeZoneHandling _dateTimeZoneHandling;

		private int? _maxDepth;

		private bool _hasExceededMaxDepth;

		internal DateParseHandling _dateParseHandling;

		internal FloatParseHandling _floatParseHandling;

		private string? _dateFormatString;

		private List<JsonPosition>? _stack;

		protected State CurrentState => _currentState;

		public bool CloseInput { get; set; }

		public bool SupportMultipleContent { get; set; }

		public virtual char QuoteChar
		{
			get
			{
				return _quoteChar;
			}
			protected internal set
			{
				_quoteChar = value;
			}
		}

		public DateTimeZoneHandling DateTimeZoneHandling
		{
			get
			{
				return _dateTimeZoneHandling;
			}
			set
			{
				if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_dateTimeZoneHandling = value;
			}
		}

		public DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling;
			}
			set
			{
				if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_dateParseHandling = value;
			}
		}

		public FloatParseHandling FloatParseHandling
		{
			get
			{
				return _floatParseHandling;
			}
			set
			{
				if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_floatParseHandling = value;
			}
		}

		public string? DateFormatString
		{
			get
			{
				return _dateFormatString;
			}
			set
			{
				_dateFormatString = value;
			}
		}

		public int? MaxDepth
		{
			get
			{
				return _maxDepth;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("Value must be positive.", "value");
				}
				_maxDepth = value;
			}
		}

		public virtual JsonToken TokenType => _tokenType;

		public virtual object? Value => _value;

		public virtual Type? ValueType => _value?.GetType();

		public virtual int Depth
		{
			get
			{
				int num = _stack?.Count ?? 0;
				if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
				{
					return num;
				}
				return num + 1;
			}
		}

		public virtual string Path
		{
			get
			{
				if (_currentPosition.Type == JsonContainerType.None)
				{
					return string.Empty;
				}
				JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null);
				return JsonPosition.BuildPath(_stack, currentPosition);
			}
		}

		public CultureInfo Culture
		{
			get
			{
				return _culture ?? CultureInfo.InvariantCulture;
			}
			set
			{
				_culture = value;
			}
		}

		public virtual Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<bool>() ?? Read().ToAsync();
		}

		public async Task SkipAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (TokenType == JsonToken.PropertyName)
			{
				await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			if (JsonTokenUtils.IsStartToken(TokenType))
			{
				int depth = Depth;
				while (await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) && depth < Depth)
				{
				}
			}
		}

		internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken)
		{
			if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
			{
				throw CreateUnexpectedEndException();
			}
		}

		public virtual Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<bool?>() ?? Task.FromResult(ReadAsBoolean());
		}

		public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<byte[]>() ?? Task.FromResult(ReadAsBytes());
		}

		internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken)
		{
			List<byte> buffer = new List<byte>();
			do
			{
				if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
				{
					SetToken(JsonToken.None);
				}
			}
			while (!ReadArrayElementIntoByteArrayReportDone(buffer));
			byte[] array = buffer.ToArray();
			SetToken(JsonToken.Bytes, array, updateIndex: false);
			return array;
		}

		public virtual Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<DateTime?>() ?? Task.FromResult(ReadAsDateTime());
		}

		public virtual Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<DateTimeOffset?>() ?? Task.FromResult(ReadAsDateTimeOffset());
		}

		public virtual Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<decimal?>() ?? Task.FromResult(ReadAsDecimal());
		}

		public virtual Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return Task.FromResult(ReadAsDouble());
		}

		public virtual Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<int?>() ?? Task.FromResult(ReadAsInt32());
		}

		public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<string>() ?? Task.FromResult(ReadAsString());
		}

		internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken)
		{
			bool flag = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			if (flag)
			{
				flag = await MoveToContentAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			return flag;
		}

		internal Task<bool> MoveToContentAsync(CancellationToken cancellationToken)
		{
			JsonToken tokenType = TokenType;
			if (tokenType == JsonToken.None || tokenType == JsonToken.Comment)
			{
				return MoveToContentFromNonContentAsync(cancellationToken);
			}
			return AsyncUtils.True;
		}

		private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken)
		{
			JsonToken tokenType;
			do
			{
				if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
				{
					return false;
				}
				tokenType = TokenType;
			}
			while (tokenType == JsonToken.None || tokenType == JsonToken.Comment);
			return true;
		}

		internal JsonPosition GetPosition(int depth)
		{
			if (_stack != null && depth < _stack.Count)
			{
				return _stack[depth];
			}
			return _currentPosition;
		}

		protected JsonReader()
		{
			_currentState = State.Start;
			_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
			_dateParseHandling = DateParseHandling.DateTime;
			_floatParseHandling = FloatParseHandling.Double;
			_maxDepth = 64;
			CloseInput = true;
		}

		private void Push(JsonContainerType value)
		{
			UpdateScopeWithFinishedValue();
			if (_currentPosition.Type == JsonContainerType.None)
			{
				_currentPosition = new JsonPosition(value);
				return;
			}
			if (_stack == null)
			{
				_stack = new List<JsonPosition>();
			}
			_stack.Add(_currentPosition);
			_currentPosition = new JsonPosition(value);
			if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth)
			{
				return;
			}
			_hasExceededMaxDepth = true;
			throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
		}

		private JsonContainerType Pop()
		{
			JsonPosition currentPosition;
			if (_stack != null && _stack.Count > 0)
			{
				currentPosition = _currentPosition;
				_currentPosition = _stack[_stack.Count - 1];
				_stack.RemoveAt(_stack.Count - 1);
			}
			else
			{
				currentPosition = _currentPosition;
				_currentPosition = default(JsonPosition);
			}
			if (_maxDepth.HasValue && Depth <= _maxDepth)
			{
				_hasExceededMaxDepth = false;
			}
			return currentPosition.Type;
		}

		private JsonContainerType Peek()
		{
			return _currentPosition.Type;
		}

		public abstract bool Read();

		public virtual int? ReadAsInt32()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is int)
				{
					return (int)value;
				}
				int num;
				if (value is BigInteger bigInteger)
				{
					num = (int)bigInteger;
				}
				else
				{
					try
					{
						num = Convert.ToInt32(value, CultureInfo.InvariantCulture);
					}
					catch (Exception ex)
					{
						throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex);
					}
				}
				SetToken(JsonToken.Integer, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
			{
				string s = (string)Value;
				return ReadInt32String(s);
			}
			default:
				throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal int? ReadInt32String(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (int.TryParse(s, NumberStyles.Integer, Culture, out var result))
			{
				SetToken(JsonToken.Integer, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual string? ReadAsString()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.String:
				return (string)Value;
			default:
				if (JsonTokenUtils.IsPrimitiveToken(contentToken))
				{
					object value = Value;
					if (value != null)
					{
						string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture));
						SetToken(JsonToken.String, text, updateIndex: false);
						return text;
					}
				}
				throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		public virtual byte[]? ReadAsBytes()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.StartObject:
			{
				ReadIntoWrappedTypeObject();
				byte[] array2 = ReadAsBytes();
				ReaderReadAndAssert();
				if (TokenType != JsonToken.EndObject)
				{
					throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
				}
				SetToken(JsonToken.Bytes, array2, updateIndex: false);
				return array2;
			}
			case JsonToken.String:
			{
				string text = (string)Value;
				Guid g;
				byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray()));
				SetToken(JsonToken.Bytes, array3, updateIndex: false);
				return array3;
			}
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Bytes:
				if (Value is Guid guid)
				{
					byte[] array = guid.ToByteArray();
					SetToken(JsonToken.Bytes, array, updateIndex: false);
					return array;
				}
				return (byte[])Value;
			case JsonToken.StartArray:
				return ReadArrayIntoByteArray();
			default:
				throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal byte[] ReadArrayIntoByteArray()
		{
			List<byte> list = new List<byte>();
			do
			{
				if (!Read())
				{
					SetToken(JsonToken.None);
				}
			}
			while (!ReadArrayElementIntoByteArrayReportDone(list));
			byte[] array = list.ToArray();
			SetToken(JsonToken.Bytes, array, updateIndex: false);
			return array;
		}

		private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer)
		{
			switch (TokenType)
			{
			case JsonToken.None:
				throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
			case JsonToken.Integer:
				buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
				return false;
			case JsonToken.EndArray:
				return true;
			case JsonToken.Comment:
				return false;
			default:
				throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
			}
		}

		public virtual double? ReadAsDouble()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is double)
				{
					return (double)value;
				}
				double num = ((!(value is BigInteger bigInteger)) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)bigInteger));
				SetToken(JsonToken.Float, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
				return ReadDoubleString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal double? ReadDoubleString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result))
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual bool? ReadAsBoolean()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				bool flag = ((!(Value is BigInteger bigInteger)) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (bigInteger != 0L));
				SetToken(JsonToken.Boolean, flag, updateIndex: false);
				return flag;
			}
			case JsonToken.String:
				return ReadBooleanString((string)Value);
			case JsonToken.Boolean:
				return (bool)Value;
			default:
				throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal bool? ReadBooleanString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (bool.TryParse(s, out var result))
			{
				SetToken(JsonToken.Boolean, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual decimal? ReadAsDecimal()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is decimal)
				{
					return (decimal)value;
				}
				decimal num;
				if (value is BigInteger bigInteger)
				{
					num = (decimal)bigInteger;
				}
				else
				{
					try
					{
						num = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
					}
					catch (Exception ex)
					{
						throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex);
					}
				}
				SetToken(JsonToken.Float, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
				return ReadDecimalString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal decimal? ReadDecimalString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result))
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success)
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual DateTime? ReadAsDateTime()
		{
			switch (GetContentToken())
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Date:
				if (Value is DateTimeOffset dateTimeOffset)
				{
					SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false);
				}
				return (DateTime)Value;
			case JsonToken.String:
				return ReadDateTimeString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
			}
		}

		internal DateTime? ReadDateTimeString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt))
			{
				dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
			{
				dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual DateTimeOffset? ReadAsDateTimeOffset()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Date:
				if (Value is DateTime dateTime)
				{
					SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false);
				}
				return (DateTimeOffset)Value;
			case JsonToken.String:
			{
				string s = (string)Value;
				return ReadDateTimeOffsetString(s);
			}
			default:
				throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal DateTimeOffset? ReadDateTimeOffsetString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt))
			{
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
			{
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		internal void ReaderReadAndAssert()
		{
			if (!Read())
			{
				throw CreateUnexpectedEndException();
			}
		}

		internal JsonReaderException CreateUnexpectedEndException()
		{
			return JsonReaderException.Create(this, "Unexpected end when reading JSON.");
		}

		internal void ReadIntoWrappedTypeObject()
		{
			ReaderReadAndAssert();
			if (Value != null && Value.ToString() == "$type")
			{
				ReaderReadAndAssert();
				if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
				{
					ReaderReadAndAssert();
					if (Value.ToString() == "$value")
					{
						return;
					}
				}
			}
			throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
		}

		public void Skip()
		{
			if (TokenType == JsonToken.PropertyName)
			{
				Read();
			}
			if (JsonTokenUtils.IsStartToken(TokenType))
			{
				int depth = Depth;
				while (Read() && depth < Depth)
				{
				}
			}
		}

		protected void SetToken(JsonToken newToken)
		{
			SetToken(newToken, null, updateIndex: true);
		}

		protected void SetToken(JsonToken newToken, object? value)
		{
			SetToken(newToken, value, updateIndex: true);
		}

		protected void SetToken(JsonToken newToken, object? value, bool updateIndex)
		{
			_tokenType = newToken;
			_value = value;
			switch (newToken)
			{
			case JsonToken.StartObject:
				_currentState = State.ObjectStart;
				Push(JsonContainerType.Object);
				break;
			case JsonToken.StartArray:
				_currentState = State.ArrayStart;
				Push(JsonContainerType.Array);
				break;
			case JsonToken.StartConstructor:
				_currentState = State.ConstructorStart;
				Push(JsonContainerType.Constructor);
				break;
			case JsonToken.EndObject:
				ValidateEnd(JsonToken.EndObject);
				break;
			case JsonToken.EndArray:
				ValidateEnd(JsonToken.EndArray);
				break;
			case JsonToken.EndConstructor:
				ValidateEnd(JsonToken.EndConstructor);
				break;
			case JsonToken.PropertyName:
				_currentState = State.Property;
				_currentPosition.PropertyName = (string)value;
				break;
			case JsonToken.Raw:
			case JsonToken.Integer:
			case JsonToken.Float:
			case JsonToken.String:
			case JsonToken.Boolean:
			case JsonToken.Null:
			case JsonToken.Undefined:
			case JsonToken.Date:
			case JsonToken.Bytes:
				SetPostValueState(updateIndex);
				break;
			case JsonToken.Comment:
				break;
			}
		}

		internal void SetPostValueState(bool updateIndex)
		{
			if (Peek() != 0 || SupportMultipleContent)
			{
				_currentState = State.PostValue;
			}
			else
			{
				SetFinished();
			}
			if (updateIndex)
			{
				UpdateScopeWithFinishedValue();
			}
		}

		private void UpdateScopeWithFinishedValue()
		{
			if (_currentPosition.HasIndex)
			{
				_currentPosition.Position++;
			}
		}

		private void ValidateEnd(JsonToken endToken)
		{
			JsonContainerType jsonContainerType = Pop();
			if (GetTypeForCloseToken(endToken) != jsonContainerType)
			{
				throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType));
			}
			if (Peek() != 0 || SupportMultipleContent)
			{
				_currentState = State.PostValue;
			}
			else
			{
				SetFinished();
			}
		}

		protected void SetStateBasedOnCurrent()
		{
			JsonContainerType jsonContainerType = Peek();
			switch (jsonContainerType)
			{
			case JsonContainerType.Object:
				_currentState = State.Object;
				break;
			case JsonContainerType.Array:
				_currentState = State.Array;
				break;
			case JsonContainerType.Constructor:
				_currentState = State.Constructor;
				break;
			case JsonContainerType.None:
				SetFinished();
				break;
			default:
				throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType));
			}
		}

		private void SetFinished()
		{
			_currentState = ((!SupportMultipleContent) ? State.Finished : State.Start);
		}

		private JsonContainerType GetTypeForCloseToken(JsonToken token)
		{
			return token switch
			{
				JsonToken.EndObject => JsonContainerType.Object, 
				JsonToken.EndArray => JsonContainerType.Array, 
				JsonToken.EndConstructor => JsonContainerType.Constructor, 
				_ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), 
			};
		}

		void IDisposable.Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (_currentState != State.Closed && disposing)
			{
				Close();
			}
		}

		public virtual void Close()
		{
			_currentState = State.Closed;
			_tokenType = JsonToken.None;
			_value = null;
		}

		internal void ReadAndAssert()
		{
			if (!Read())
			{
				throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
			}
		}

		internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter)
		{
			if (!ReadForType(contract, hasConverter))
			{
				throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
			}
		}

		internal bool ReadForType(JsonContract? contract, bool hasConverter)
		{
			if (hasConverter)
			{
				return Read();
			}
			switch (contract?.InternalReadType ?? ReadType.Read)
			{
			case ReadType.Read:
				return ReadAndMoveToContent();
			case ReadType.ReadAsInt32:
				ReadAsInt32();
				break;
			case ReadType.ReadAsInt64:
			{
				bool result = ReadAndMoveToContent();
				if (TokenType == JsonToken.Undefined)
				{
					throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long)));
				}
				return result;
			}
			case ReadType.ReadAsDecimal:
				ReadAsDecimal();
				break;
			case ReadType.ReadAsDouble:
				ReadAsDouble();
				break;
			case ReadType.ReadAsBytes:
				ReadAsBytes();
				break;
			case ReadType.ReadAsBoolean:
				ReadAsBoolean();
				break;
			case ReadType.ReadAsString:
				ReadAsString();
				break;
			case ReadType.ReadAsDateTime:
				ReadAsDateTime();
				break;
			case ReadType.ReadAsDateTimeOffset:
				ReadAsDateTimeOffset();
				break;
			default:
				throw new ArgumentOutOfRangeException();
			}
			return TokenType != JsonToken.None;
		}

		internal bool ReadAndMoveToContent()
		{
			if (Read())
			{
				return MoveToContent();
			}
			return false;
		}

		internal bool MoveToContent()
		{
			JsonToken tokenType = TokenType;
			while (tokenType == JsonToken.None || tokenType == JsonToken.Comment)
			{
				if (!Read())
				{
					return false;
				}
				tokenType = TokenType;
			}
			return true;
		}

		private JsonToken GetContentToken()
		{
			JsonToken tokenType;
			do
			{
				if (!Read())
				{
					SetToken(JsonToken.None);
					return JsonToken.None;
				}
				tokenType = TokenType;
			}
			while (tokenType == JsonToken.Comment);
			return tokenType;
		}
	}
	[Serializable]
	public class JsonReaderException : JsonException
	{
		public int LineNumber { get; }

		public int LinePosition { get; }

		public string? Path { get; }

		public JsonReaderException()
		{
		}

		public JsonReaderException(string message)
			: base(message)
		{
		}

		public JsonReaderException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public JsonReaderException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
			: base(message, innerException)
		{
			Path = path;
			LineNumber = lineNumber;
			LinePosition = linePosition;
		}

		internal static JsonReaderException Create(JsonReader reader, string message)
		{
			return Create(reader, message, null);
		}

		internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex)
		{
			return Create(reader as IJsonLineInfo, reader.Path, message, ex);
		}

		internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			int lineNumber;
			int linePosition;
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				lineNumber = lineInfo.LineNumber;
				linePosition = lineInfo.LinePosition;
			}
			else
			{
				lineNumber = 0;
				linePosition = 0;
			}
			return new JsonReaderException(message, path, lineNumber, linePosition, ex);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class JsonRequiredAttribute : Attribute
	{
	}
	[Serializable]
	public class JsonSerializationException : JsonException
	{
		public int LineNumber { get; }

		public int LinePosition { get; }

		public string? Path { get; }

		public JsonSerializationException()
		{
		}

		public JsonSerializationException(string message)
			: base(message)
		{
		}

		public JsonSerializationException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public JsonSerializationException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
			: base(message, innerException)
		{
			Path = path;
			LineNumber = lineNumber;
			LinePosition = linePosition;
		}

		internal static JsonSerializationException Create(JsonReader reader, string message)
		{
			return Create(reader, message, null);
		}

		internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex)
		{
			return Create(reader as IJsonLineInfo, reader.Path, message, ex);
		}

		internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			int lineNumber;
			int linePosition;
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				lineNumber = lineInfo.LineNumber;
				linePosition = lineInfo.LinePosition;
			}
			else
			{
				lineNumber = 0;
				linePosition = 0;
			}
			return new JsonSerializationException(message, path, lineNumber, linePosition, ex);
		}
	}
	public class JsonSerializer
	{
		internal TypeNameHandling _typeNameHandling;

		internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling;

		internal PreserveReferencesHandling _preserveReferencesHandling;

		internal ReferenceLoopHandling _referenceLoopHandling;

		internal MissingMemberHandling _missingMemberHandling;

		internal ObjectCreationHandling _objectCreationHandling;

		internal NullValueHandling _nullValueHandling;

		internal DefaultValueHandling _defaultValueHandling;

		internal ConstructorHandling _constructorHandling;

		internal MetadataPropertyHandling _metadataPropertyHandling;

		internal JsonConverterCollection? _converters;

		internal IContractResolver _contractResolver;

		internal ITraceWriter? _traceWriter;

		internal IEqualityComparer? _equalityComparer;

		internal ISerializationBinder _serializationBinder;

		internal StreamingContext _context;

		private IReferenceResolver? _referenceResolver;

		private Formatting? _formatting;

		private DateFormatHandling? _dateFormatHandling;

		private DateTimeZoneHandling? _dateTimeZoneHandling;

		private DateParseHandling? _dateParseHandling;

		private FloatFormatHandling? _floatFormatHandling;

		private FloatParseHandling? _floatParseHandling;

		private StringEscapeHandling? _stringEscapeHandling;

		private CultureInfo _culture;

		private int? _maxDepth;

		private bool _maxDepthSet;

		private bool? _checkAdditionalContent;

		private string? _dateFormatString;

		private bool _dateFormatStringSet;

		public virtual IReferenceResolver? ReferenceResolver
		{
			get
			{
				return GetReferenceResolver();
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Reference resolver cannot be null.");
				}
				_referenceResolver = value;
			}
		}

		[Obsolete("Binder is obsolete. Use SerializationBinder instead.")]
		public virtual SerializationBinder Binder
		{
			get
			{
				if (_serializationBinder is SerializationBinder result)
				{
					return result;
				}
				if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter)
				{
					return serializationBinderAdapter.SerializationBinder;
				}
				throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set.");
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Serialization binder cannot be null.");
				}
				_serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value);
			}
		}

		public virtual ISerializationBinder SerializationBinder
		{
			get
			{
				return _serializationBinder;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Serialization binder cannot be null.");
				}
				_serializationBinder = value;
			}
		}

		public virtual ITraceWriter? TraceWriter
		{
			get
			{
				return _traceWriter;
			}
			set
			{
				_traceWriter = value;
			}
		}

		public virtual IEqualityComparer? EqualityComparer
		{
			get
			{
				return _equalityComparer;
			}
			set
			{
				_equalityComparer = value;
			}
		}

		public virtual TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling;
			}
			set
			{
				if (value < TypeNameHandling.None || value > TypeNameHandling.Auto)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameHandling = value;
			}
		}

		[Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")]
		public virtual FormatterAssemblyStyle TypeNameAssemblyFormat
		{
			get
			{
				return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling;
			}
			set
			{
				if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value;
			}
		}

		public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling
		{
			get
			{
				return _typeNameAssemblyFormatHandling;
			}
			set
			{
				if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameAssemblyFormatHandling = value;
			}
		}

		public virtual PreserveReferencesHandling PreserveReferencesHandling
		{
			get
			{
				return _preserveReferencesHandling;
			}
			set
			{
				if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_preserveReferencesHandling = value;
			}
		}

		public virtual ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling;
			}
			set
			{
				if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_referenceLoopHandling = value;
			}
		}

		public virtual MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling;
			}
			set
			{
				if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_missingMemberHandling = value;
			}
		}

		public virtual NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling;
			}
			set
			{
				if (value < NullValueHandling.Include || value > NullValueHandling.Ignore)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_nullValueHandling = value;
			}
		}

		public virtual DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling;
			}
			set
			{
				if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_defaultValueHandling = value;
			}
		}

		public virtual ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling;
			}
			set
			{
				if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_objectCreationHandling = value;
			}
		}

		public virtual ConstructorHandling ConstructorHandling
		{
			get
			{
				return _constructorHandling;
			}
			set
			{
				if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_constructorHandling = value;
			}
		}

		public virtual MetadataPropertyHandling MetadataPropertyHandling
		{
			get
			{
				return _metadataPropertyHandling;
			}
			set
			{
				if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_metadataPropertyHandling = value;
			}
		}

		public virtual JsonConverterCollection Converters
		{
			get
			{
				if (_converters == null)
				{
					_converters = new JsonConverterCollection();
				}
				return _converters;
			}
		}

		public virtual IContractResolver ContractResolver
		{
			get
			{
				return _contractResolver;
			}
			set
			{
				_contractResolver = value ?? DefaultContractResolver.Instance;
			}
		}

		public virtual StreamingContext Context
		{
			get
			{
				return _context;
			}
			set
			{
				_context = value;
			}
		}

		public virtual Formatting Formatting
		{
			get
			{
				return _formatting.GetValueOrDefault();
			}
			set
			{
				_formatting = value;
			}
		}

		public virtual DateFormatHandling DateFormatHandling
		{
			get
			{
				return _dateFormatHandling.GetValueOrDefault();
			}
			set
			{
				_dateFormatHandling = value;
			}
		}

		public virtual DateTimeZoneHandling DateTimeZoneHandling
		{
			get
			{
				return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind;
			}
			set
			{
				_dateTimeZoneHandling = value;
			}
		}

		public virtual DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling ?? DateParseHandling.DateTime;
			}
			set
			{
				_dateParseHandling = value;
			}
		}

		public virtual FloatParseHandling FloatParseHandling
		{
			get
			{
				return _floatParseHandling.GetValueOrDefault();
			}
			set
			{
				_floatParseHandling = value;
			}
		}

		public virtual FloatFormatHandling FloatFormatHandling
		{
			get
			{
				return _floatFormatHandling.GetValueOrDefault();
			}
			set
			{
				_floatFormatHandling = value;
			}
		}

		public virtual StringEscapeHandling StringEscapeHandling
		{
			get
			{
				return _stringEscapeHandling.GetValueOrDefault();
			}
			set
			{
				_stringEscapeHandling = value;
			}
		}

		public virtual string DateFormatString
		{
			get
			{
				return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
			}
			set
			{
				_dateFormatString = value;
				_dateFormatStringSet = true;
			}
		}

		public virtual CultureInfo Culture
		{
			get
			{
				return _culture ?? JsonSerializerSettings.DefaultCulture;
			}
			set
			{
				_culture = value;
			}
		}

		public virtual int? MaxDepth
		{
			get
			{
				return _maxDepth;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("Value must be positive.", "value");
				}
				_maxDepth = value;
				_maxDepthSet = true;
			}
		}

		public virtual bool CheckAdditionalContent
		{
			get
			{
				return _checkAdditionalContent.GetValueOrDefault();
			}
			set
			{
				_checkAdditionalContent = value;
			}
		}

		public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error;

		internal bool IsCheckAdditionalContentSet()
		{
			return _checkAdditionalContent.HasValue;
		}

		public JsonSerializer()
		{
			_referenceLoopHandling = ReferenceLoopHandling.Error;
			_missingMemberHandling = MissingMemberHandling.Ignore;
			_nullValueHandling = NullValueHandling.Include;
			_defaultValueHandling = DefaultValueHandling.Include;
			_objectCreationHandling = ObjectCreationHandling.Auto;
			_preserveReferencesHandling = PreserveReferencesHandling.None;
			_constructorHandling = ConstructorHandling.Default;
			_typeNameHandling = TypeNameHandling.None;
			_metadataPropertyHandling = MetadataPropertyHandling.Default;
			_context = JsonSerializerSettings.DefaultContext;
			_serializationBinder = DefaultSerializationBinder.Instance;
			_culture = JsonSerializerSettings.DefaultCulture;
			_contractResolver = DefaultContractResolver.Instance;
		}

		public static JsonSerializer Create()
		{
			return new JsonSerializer();
		}

		public static JsonSerializer Create(JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = Create();
			if (settings != null)
			{
				ApplySerializerSettings(jsonSerializer, settings);
			}
			return jsonSerializer;
		}

		public static JsonSerializer CreateDefault()
		{
			return Create(JsonConvert.DefaultSettings?.Invoke());
		}

		public static JsonSerializer CreateDefault(JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = CreateDefault();
			if (settings != null)
			{
				ApplySerializerSettings(jsonSerializer, settings);
			}
			return jsonSerializer;
		}

		private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings)
		{
			if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
			{
				for (int i = 0; i < settings.Converters.Count; i++)
				{
					serializer.Converters.Insert(i, settings.Converters[i]);
				}
			}
			if (settings._typeNameHandling.HasValue)
			{
				serializer.TypeNameHandling = settings.TypeNameHandling;
			}
			if (settings._metadataPropertyHandling.HasValue)
			{
				serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling;
			}
			if (settings._typeNameAssemblyFormatHandling.HasValue)
			{
				serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling;
			}
			if (settings._preserveReferencesHandling.HasValue)
			{
				serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling;
			}
			if (settings._referenceLoopHandling.HasValue)
			{
				serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling;
			}
			if (settings._missingMemberHandling.HasValue)
			{
				serializer.MissingMemberHandling = settings.MissingMemberHandling;
			}
			if (settings._objectCreationHandling.HasValue)
			{
				serializer.ObjectCreationHandling = settings.ObjectCreationHandling;
			}
			if (settings._nullValueHandling.HasValue)
			{
				serializer.NullValueHandling = settings.NullValueHandling;
			}
			if (settings._defaultValueHandling.HasValue)
			{
				serializer.DefaultValueHandling = settings.DefaultValueHandling;
			}
			if (settings._constructorHandling.HasValue)
			{
				serializer.ConstructorHandling = settings.ConstructorHandling;
			}
			if (settings._context.HasValue)
			{
				serializer.Context = settings.Context;
			}
			if (settings._checkAdditionalContent.HasValue)
			{
				serializer._checkAdditionalContent = settings._checkAdditionalContent;
			}
			if (settings.Error != null)
			{
				serializer.Error += settings.Error;
			}
			if (settings.ContractResolver != null)
			{
				serializer.ContractResolver = settings.ContractResolver;
			}
			if (settings.ReferenceResolverProvider != null)
			{
				serializer.ReferenceResolver = settings.ReferenceResolverProvider();
			}
			if (settings.TraceWriter != null)
			{
				serializer.TraceWriter = settings.TraceWriter;
			}
			if (settings.EqualityComparer != null)
			{
				serializer.EqualityComparer = settings.EqualityComparer;
			}
			if (settings.SerializationBinder != null)
			{
				serializer.SerializationBinder = settings.SerializationBinder;
			}
			if (settings._formatting.HasValue)
			{
				serializer._formatting = settings._formatting;
			}
			if (settings._dateFormatHandling.HasValue)
			{
				serializer._dateFormatHandling = settings._dateFormatHandling;
			}
			if (settings._dateTimeZoneHandling.HasValue)
			{
				serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling;
			}
			if (settings._dateParseHandling.HasValue)
			{
				serializer._dateParseHandling = settings._dateParseHandling;
			}
			if (settings._dateFormatStringSet)
			{
				serializer._dateFormatString = settings._dateFormatString;
				serializer._dateFormatStringSet = settings._dateFormatStringSet;
			}
			if (settings._floatFormatHandling.HasValue)
			{
				serializer._floatFormatHandling = settings._floatFormatHandling;
			}
			if (settings._floatParseHandling.HasValue)
			{
				serializer._floatParseHandling = settings._floatParseHandling;
			}
			if (settings._stringEscapeHandling.HasValue)
			{
				serializer._stringEscapeHandling = settings._stringEscapeHandling;
			}
			if (settings._culture != null)
			{
				serializer._culture = settings._culture;
			}
			if (settings._maxDepthSet)
			{
				serializer._maxDepth = settings._maxDepth;
				serializer._maxDepthSet = settings._maxDepthSet;
			}
		}

		[DebuggerStepThrough]
		public void Populate(TextReader reader, object target)
		{
			Populate(new JsonTextReader(reader), target);
		}

		[DebuggerStepThrough]
		public void Populate(JsonReader reader, object target)
		{
			PopulateInternal(reader, target);
		}

		internal virtual void PopulateInternal(JsonReader reader, object target)
		{
			ValidationUtils.ArgumentNotNull(reader, "reader");
			ValidationUtils.ArgumentNotNull(target, "target");
			SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString);
			TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null);
			new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target);
			if (traceJsonReader != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
			}
			ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
		}

		[DebuggerStepThrough]
		public object? Deserialize(JsonReader reader)
		{
			return Deserialize(reader, null);
		}

		[DebuggerStepThrough]
		public object? Deserialize(TextReader reader, Type objectType)
		{
			return Deserialize(new JsonTextReader(reader), objectType);
		}

		[DebuggerStepThrough]
		public T? Deserialize<T>(JsonReader reader)
		{
			return (T)Deserialize(reader, typeof(T));
		}

		[DebuggerStepThrough]
		public object? Deserialize(JsonReader reader, Type? objectType)
		{
			return DeserializeInternal(reader, objectType);
		}

		internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType)
		{
			ValidationUtils.ArgumentNotNull(reader, "reader");
			SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString);
			TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null);
			object? result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent);
			if (traceJsonReader != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
			}
			ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
			return result;
		}

		internal void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString)
		{
			if (_culture != null && !_culture.Equals(reader.Culture))
			{
				previousCulture = reader.Culture;
				reader.Culture = _culture;
			}
			else
			{
				previousCulture = null;
			}
			if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling)
			{
				previousDateTimeZoneHandling = reader.DateTimeZoneHandling;
				reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault();
			}
			else
			{
				previousDateTimeZoneHandling = null;
			}
			if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling)
			{
				previousDateParseHandling = reader.DateParseHandling;
				reader.DateParseHandling = _dateParseHandling.GetValueOrDefault();
			}
			else
			{
				previousDateParseHandling = null;
			}
			if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling)
			{
				previousFloatParseHandling = reader.FloatParseHandling;
				reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault();
			}
			else
			{
				previousFloatParseHandling = null;
			}
			if (_maxDepthSet && reader.MaxDepth != _maxDepth)
			{
				previousMaxDepth = reader.MaxDepth;
				reader.MaxDepth = _maxDepth;
			}
			else
			{
				previousMaxDepth = null;
			}
			if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString)
			{
				previousDateFormatString = reader.DateFormatString;
				reader.DateFormatString = _dateFormatString;
			}
			else
			{
				previousDateFormatString = null;
			}
			if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable == null && _contractResolver is DefaultContractResolver defaultContractResolver)
			{
				jsonTextReader.PropertyNameTable = defaultContractResolver.GetNameTable();
			}
		}

		private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString)
		{
			if (previousCulture != null)
			{
				reader.Culture = previousCulture;
			}
			if (previousDateTimeZoneHandling.HasValue)
			{
				reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault();
			}
			if (previousDateParseHandling.HasValue)
			{
				reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault();
			}
			if (previousFloatParseHandling.HasValue)
			{
				reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault();
			}
			if (_maxDepthSet)
			{
				reader.MaxDepth = previousMaxDepth;
			}
			if (_dateFormatStringSet)
			{
				reader.DateFormatString = previousDateFormatString;
			}
			if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable != null && _contractResolver is DefaultContractResolver defaultContractResolver && jsonTextReader.PropertyNameTable == defaultContractResolver.GetNameTable())
			{
				jsonTextReader.PropertyNameTable = null;
			}
		}

		public void Serialize(TextWriter textWriter, object? value)
		{
			Serialize(new JsonTextWriter(textWriter), value);
		}

		public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType)
		{
			SerializeInternal(jsonWriter, value, objectType);
		}

		public void Serialize(TextWriter textWriter, object? value, Type objectType)
		{
			Serialize(new JsonTextWriter(textWriter), value, objectType);
		}

		public void Serialize(JsonWriter jsonWriter, object? value)
		{
			SerializeInternal(jsonWriter, value, null);
		}

		private TraceJsonReader CreateTraceJsonReader(JsonReader reader)
		{
			TraceJsonReader traceJsonReader = new TraceJsonReader(reader);
			if (reader.TokenType != 0)
			{
				traceJsonReader.WriteCurrentToken();
			}
			return traceJsonReader;
		}

		internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType)
		{
			ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter");
			Formatting? formatting = null;
			if (_formatting.HasValue && jsonWriter.Formatting != _formatting)
			{
				formatting = jsonWriter.Formatting;
				jsonWriter.Formatting = _formatting.GetValueOrDefault();
			}
			DateFormatHandling? dateFormatHandling = null;
			if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling)
			{
				dateFormatHandling = jsonWriter.DateFormatHandling;
				jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault();
			}
			DateTimeZoneHandling? dateTimeZoneHandling = null;
			if (_dateTimeZoneHandling.HasValue && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling)
			{
				dateTimeZoneHandling = jsonWriter.DateTimeZoneHandling;
				jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault();
			}
			FloatFormatHandling? floatFormatHandling = null;
			if (_floatFormatHandling.HasValue && jsonWriter.FloatFormatHandling != _floatFormatHandling)
			{
				floatFormatHandling = jsonWriter.FloatFormatHandling;
				jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault();
			}
			StringEscapeHandling? stringEscapeHandling = null;
			if (_stringEscapeHandling.HasValue && jsonWriter.StringEscapeHandling != _stringEscapeHandling)
			{
				stringEscapeHandling = jsonWriter.StringEscapeHandling;
				jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault();
			}
			CultureInfo cultureInfo = null;
			if (_culture != null && !_culture.Equals(jsonWriter.Culture))
			{
				cultureInfo = jsonWriter.Culture;
				jsonWriter.Culture = _culture;
			}
			string dateFormatString = null;
			if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString)
			{
				dateFormatString = jsonWriter.DateFormatString;
				jsonWriter.DateFormatString = _dateFormatString;
			}
			TraceJsonWriter traceJsonWriter = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null);
			new JsonSerializerInternalWriter(this).Serialize(traceJsonWriter ?? jsonWriter, value, objectType);
			if (traceJsonWriter != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null);
			}
			if (formatting.HasValue)
			{
				jsonWriter.Formatting = formatting.GetValueOrDefault();
			}
			if (dateFormatHandling.HasValue)
			{
				jsonWriter.DateFormatHandling = dateFormatHandling.GetValueOrDefault();
			}
			if (dateTimeZoneHandling.HasValue)
			{
				jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling.GetValueOrDefault();
			}
			if (floatFormatHandling.HasValue)
			{
				jsonWriter.FloatFormatHandling = floatFormatHandling.GetValueOrDefault();
			}
			if (stringEscapeHandling.HasValue)
			{
				jsonWriter.StringEscapeHandling = stringEscapeHandling.GetValueOrDefault();
			}
			if (_dateFormatStringSet)
			{
				jsonWriter.DateFormatString = dateFormatString;
			}
			if (cultureInfo != null)
			{
				jsonWriter.Culture = cultureInfo;
			}
		}

		internal IReferenceResolver GetReferenceResolver()
		{
			if (_referenceResolver == null)
			{
				_referenceResolver = new DefaultReferenceResolver();
			}
			return _referenceResolver;
		}

		internal JsonConverter? GetMatchingConverter(Type type)
		{
			return GetMatchingConverter(_converters, type);
		}

		internal static JsonConverter? GetMatchingConverter(IList<JsonConverter>? converters, Type objectType)
		{
			if (converters != null)
			{
				for (int i = 0; i < converters.Count; i++)
				{
					JsonConverter jsonConverter = converters[i];
					if (jsonConverter.CanConvert(objectType))
					{
						return jsonConverter;
					}
				}
			}
			return null;
		}

		internal void OnError(Newtonsoft.Json.Serialization.ErrorEventArgs e)
		{
			this.Error?.Invoke(this, e);
		}
	}
	public class JsonSerializerSettings
	{
		internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error;

		internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore;

		internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include;

		internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include;

		internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto;

		internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None;

		internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default;

		internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None;

		internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default;

		internal static readonly StreamingContext DefaultContext;

		internal const Formatting DefaultFormatting = Formatting.None;

		internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat;

		internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;

		internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime;

		internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double;

		internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String;

		internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default;

		internal const TypeNameAssemblyFormatHandling DefaultTypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple;

		internal static readonly CultureInfo DefaultCulture;

		internal const bool DefaultCheckAdditionalContent = false;

		internal const string DefaultDateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";

		internal const int DefaultMaxDepth = 64;

		internal Formatting? _formatting;

		internal DateFormatHandling? _dateFormatHandling;

		internal DateTimeZoneHandling? _dateTimeZoneHandling;

		internal DateParseHandling? _dateParseHandling;

		internal FloatFormatHandling? _floatFormatHandling;

		internal FloatParseHandling? _floatParseHandling;

		internal StringEscapeHandling? _stringEscapeHandling;

		internal CultureInfo? _culture;

		internal bool? _checkAdditionalContent;

		internal int? _maxDepth;

		internal bool _maxDepthSet;

		internal string? _dateFormatString;

		internal bool _dateFormatStringSet;

		internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling;

		internal DefaultValueHandling? _defaultValueHandling;

		internal PreserveReferencesHandling? _preserveReferencesHandling;

		internal NullValueHandling? _nullValueHandling;

		internal ObjectCreationHandling? _objectCreationHandling;

		internal MissingMemberHandling? _missingMemberHandling;

		internal ReferenceLoopHandling? _referenceLoopHandling;

		internal StreamingContext? _context;

		internal ConstructorHandling? _constructorHandling;

		internal TypeNameHandling? _typeNameHandling;

		internal MetadataPropertyHandling? _metadataPropertyHandling;

		public ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_referenceLoopHandling = value;
			}
		}

		public MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling.GetValueOrDefault();
			}
			set
			{
				_missingMemberHandling = value;
			}
		}

		public ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling.GetValueOrDefault();
			}
			set
			{
				_objectCreationHandling = value;
			}
		}

		public NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling.GetValueOrDefault();
			}
			set
			{
				_nullValueHandling = value;
			}
		}

		public DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling.GetValueOrDefault();
			}
			set
			{
				_defaultValueHandling = value;
			}
		}

		public IList<JsonConverter> Converters { get; set; }

		public PreserveReferencesHandling PreserveReferencesHandling
		{
			get
			{
				return _preserveReferencesHandling.GetValueOrDefault();
			}
			set
			{
				_preserveReferencesHandling = value;
			}
		}

		public TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling.GetValueOrDefault();
			}
			set
			{